2008-10-01 62 views
12

我有以下格式的數據庫:透視表和串聯列

ID TYPE SUBTYPE COUNT MONTH 
1  A  Z   1  7/1/2008 
1  A  Z   3  7/1/2008 
2  B  C   2  7/2/2008 
1  A  Z   3  7/2/2008 

我可以使用SQL將其轉換成這樣:

ID A_Z B_C MONTH 
1  4  0  7/1/2008 
2  0  2  7/2/2008 
1  0  3  7/2/2008 

所以,TYPESUBTYPE連接成在IDMONTH匹配的情況下,新列和COUNT被求和。

任何提示將不勝感激。這可能在SQL中,或者我應該手動編程嗎?

的數據庫是SQL Server 2005中

假設有這樣和「A」和「Z」不應該被硬編碼,但動態生成的TYPESSUBTYPES 100S。

回答

28

SQL Server 2005中提供了一個非常有用的PIVOT和UNPIVOT運算符,它讓你做出使用PIVOT和一些代碼生成/動態SQL

/* 
CREATE TABLE [dbo].[stackoverflow_159456](
    [ID] [int] NOT NULL, 
    [TYPE] [char](1) NOT NULL, 
    [SUBTYPE] [char](1) NOT NULL, 
    [COUNT] [int] NOT NULL, 
    [MONTH] [datetime] NOT NULL 
) ON [PRIMARY] 
*/ 

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) 
+0

謝謝你救了這個代碼免維護我天! – TheVillageIdiot 2011-03-01 09:28:17

6
select id, 
sum(case when type = 'A' and subtype = 'Z' then [count] else 0 end) as A_Z, 
sum(case when type = 'B' and subtype = 'C' then [count] else 0 end) as B_C, 
month 
from tbl_why_would_u_do_this 
group by id, month 

您比我們的營銷團隊更改需求!如果你希望它是動態的,你需要回到一個存儲過程。

+3

+1的tbl_why_would_u_do_this – 2008-10-01 20:16:58