Home > Database > Mysql Tutorial > How to Pivot Data with an Unknown Number of Columns in SQL Server 2005?

How to Pivot Data with an Unknown Number of Columns in SQL Server 2005?

Patricia Arquette
Release: 2025-01-13 07:24:42
Original
892 people have browsed it

How to Pivot Data with an Unknown Number of Columns in SQL Server 2005?

Pivot Data Handling Unknown Number of Columns in SQL Server 2005

This article explores the pivoting challenges of handling data with an unknown number of columns in SQL Server 2005. The given data set contains columns of variables representing assignments and grades, and the desired output is a pivot table containing columns for assignments and total student scores.

Due to SQL Server 2005 limitations, a pure SQL (no dynamic SQL) solution is not possible for this task. As mentioned in the suggested answer, dynamic SQL provides a way to dynamically generate the necessary statements based on the current data.

For example, if a table named Assignments contains assignment names and due dates:

<code class="language-sql">CREATE TABLE Assignments (
  ID int NOT NULL,
  AssignmentName varchar(50) NOT NULL,
  DueDate datetime
);</code>
Copy after login

and data:

<code class="language-sql">INSERT INTO Assignments (ID, AssignmentName, DueDate) VALUES (1, 'Assignment 1', '2023-03-01'), (2, 'Assignment 2', '2023-04-01'), (3, 'Assignment 3', '2023-05-01');</code>
Copy after login

The required output can be generated using the following dynamic SQL:

<code class="language-sql">DECLARE @cols AS NVARCHAR(MAX),
        @query AS NVARCHAR(MAX);

SET @cols = (SELECT STUFF((
  SELECT ',[' + AssignmentName + ']'
  FROM Assignments
  FOR XML PATH(''), TYPE
), 1, 1, ''));

SET @query = 'SELECT
  StudentName,
  ' + @cols + ',
  SUM(Grade) OVER (PARTITION BY StudentName) AS Total
FROM
  (SELECT
    StudentName,
    AssignmentName,
    CASE WHEN AssignmentName = ''Total'' THEN NULL ELSE Grade END AS Grade
  FROM
    YourTable) AS t
PIVOT
  (MAX(Grade)
  FOR AssignmentName IN (' + @cols + ')) AS pvt';

EXECUTE(@query);</code>
Copy after login

This will create a pivot table with the assignment column and student total score, sorted by due date (if the DueDate column exists in the table).

The above is the detailed content of How to Pivot Data with an Unknown Number of Columns in SQL Server 2005?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template