Home > Database > Mysql Tutorial > How to Pivot and Concatenate Columns in SQL Server Using the PIVOT Operator?

How to Pivot and Concatenate Columns in SQL Server Using the PIVOT Operator?

Mary-Kate Olsen
Release: 2025-01-01 12:23:13
Original
729 people have browsed it

How to Pivot and Concatenate Columns in SQL Server Using the PIVOT Operator?

Pivot Table and Concatenate Columns in SQL Server

The given SQL Server database contains records with ID, TYPE, SUBTYPE, COUNT, and MONTH columns. The goal is to transform this data into a pivoted table where TYPE and SUBTYPE are concatenated into new columns and COUNT is summed for matching ID and MONTH values.

To achieve this, SQL Server provides the PIVOT operator, which dynamically generates columns based on provided values. Here's how you can approach this problem using PIVOT:

DECLARE @sql AS VARCHAR(MAX);
DECLARE @pivot_list AS VARCHAR(MAX);
DECLARE @select_list AS VARCHAR(MAX);

SELECT @pivot_list = COALESCE(@pivot_list + ', ', '') + '[' + PIVOT_CODE + ']',
       @select_list = COALESCE(@select_list + ', ', '') + 'ISNULL([' + PIVOT_CODE + '], 0) AS [' + PIVOT_CODE + ']'
FROM (
    SELECT DISTINCT [TYPE] + '_' + SUBTYPE AS PIVOT_CODE
    FROM TableName
) AS PIVOT_CODES;

SET @sql = ';WITH p AS (
    SELECT ID, [MONTH], [TYPE] + ''_'' + SUBTYPE AS PIVOT_CODE, SUM([COUNT]) AS [COUNT]
    FROM TableName
    GROUP BY ID, [MONTH], [TYPE] + ''_'' + SUBTYPE
)
SELECT ID, [MONTH], ' + @select_list + '
FROM p
PIVOT (
    SUM([COUNT])
    FOR PIVOT_CODE IN (
        ' + @pivot_list + '
    )
) AS pvt';

EXEC (@sql);
Copy after login

This code dynamically generates the required column list and uses the PIVOT operator to create the pivoted table. The resulting output will have the desired format with concatenated TYPE and SUBTYPE columns and summed COUNT values.

The above is the detailed content of How to Pivot and Concatenate Columns in SQL Server Using the PIVOT Operator?. 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