Concatenating Columns and Pivoting Data with SQL
Problem:
You have a database with columns representing ID, type, subtype, count, and month. How can you convert this data into a new format where the type and subtype are concatenated into new columns and the count is summed for each unique combination of ID and month?
Solution:
To achieve this transformed output, you can utilize the PIVOT operator in SQL Server 2005. The PIVOT operator allows you to dynamically transpose rows into columns.
The following code snippet demonstrates how to use PIVOT to achieve the desired result:
DECLARE @sql AS varchar(max) DECLARE @pivot_list AS varchar(max) -- Leave NULL for COALESCE technique DECLARE @select_list AS varchar(max) -- Leave NULL for COALESCE technique 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 stackoverflow_159456 ) AS PIVOT_CODES SET @sql = ' ;WITH p AS ( SELECT ID, [MONTH], [TYPE] + ''_'' + SUBTYPE AS PIVOT_CODE, SUM([COUNT]) AS [COUNT] FROM stackoverflow_159456 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)
Implementation Details:
Executing the @sql variable will return the desired table with concatenated columns and summed counts. This solution allows for efficient and dynamic aggregation of complex data.
The above is the detailed content of How can SQL be used to concatenate columns, pivot data, and sum counts for unique ID and month combinations?. For more information, please follow other related articles on the PHP Chinese website!