Home > Database > Mysql Tutorial > How to Dynamically Pivot a SQL Server Table with Varying Categories?

How to Dynamically Pivot a SQL Server Table with Varying Categories?

DDD
Release: 2025-01-25 18:47:11
Original
544 people have browsed it

How to Dynamically Pivot a SQL Server Table with Varying Categories?

Use dynamic SQL to achieve data perspective

Question:

The data set containing the date, category, and amount column is converted into a perspective table with dynamic categories. For example, the following data:

Need to be converted to:

<code>日期        类别        金额
2012年1月1日    ABC             1000.00
2012年2月1日    DEF             500.00
2012年2月1日    GHI             800.00
2012年2月10日   DEF             700.00
2012年3月1日    ABC             1100.00</code>
Copy after login
Solution:

<code>日期        ABC             DEF             GHI
2012年1月1日    1000.00
2012年2月1日                    500.00        800.00
2012年2月10日                   700.00
2012年3月1日    1100.00</code>
Copy after login
SQL Server provides dynamic perspective functions that can be used to achieve this conversion. The following script demonstrates how to achieve:

This method uses a dynamic SQL to retrieve different categories from the table. Then, it dynamically constructs Pivot clauses to consider all unique categories. Then see the result accordingly, align data and category data.

Result:

<code class="language-sql">CREATE TABLE temp (
    date DATETIME,
    category VARCHAR(3),
    amount MONEY
);

INSERT INTO temp VALUES ('2012-01-01', 'ABC', 1000.00);
INSERT INTO temp VALUES ('2012-02-01', 'DEF', 500.00);
INSERT INTO temp VALUES ('2012-02-01', 'GHI', 800.00);
INSERT INTO temp VALUES ('2012-02-10', 'DEF', 700.00);
INSERT INTO temp VALUES ('2012-03-01', 'ABC', 1100.00);


DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.category) 
            FROM temp c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'');

SET @query = 'SELECT date, ' + @cols + ' FROM 
            (
                SELECT date, amount, category
                FROM temp
           ) x
            PIVOT 
            (
                 MAX(amount)
                FOR category IN (' + @cols + ')
            ) p ';


EXECUTE(@query);

DROP TABLE temp;</code>
Copy after login

The above is the detailed content of How to Dynamically Pivot a SQL Server Table with Varying Categories?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template