gpt4 book ai didi

sql - 数据透视表和连接列

转载 作者:太空狗 更新时间:2023-10-30 01:41:44 25 4
gpt4 key购买 nike

我有以下格式的数据库:

 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 被连接到新的列中,COUNTIDMONTH 匹配。

如有任何提示,我们将不胜感激。这在 SQL 中可行还是我应该手动编程?

数据库是SQL Server 2005。

假设有 100 个 TYPESSUBTYPES,那么“A”和“Z”不应该是硬编码的,而是动态生成的。

最佳答案

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)

关于sql - 数据透视表和连接列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/159456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com