Tabella pivot e colonne concatenate
-
03-07-2019 - |
Domanda
Ho un database nel seguente formato:
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
Posso usare SQL per convertirlo in questo:
ID A_Z B_C MONTH
1 4 0 7/1/2008
2 0 2 7/2/2008
1 0 3 7/2/2008
Quindi, TYPE
, SUBTYPE
sono concatenati in nuove colonne e COUNT
viene sommato dove ID
e MONTH
corrisponde.
Eventuali suggerimenti sarebbero apprezzati. È possibile in SQL o devo programmarlo manualmente?
Il database è SQL Server 2005.
Supponi che ci siano centinaia di TYPES
e SUBTYPES
, quindi 'A' e 'Z' non dovrebbero essere codificati ma generati dinamicamente.
Soluzione
SQL Server 2005 offre un operatore PIVOT e UNPIVOT molto utile che consente di rendere questo codice esente da manutenzione utilizzando PIVOT e alcuni SQL / generazione dinamica di codice
/*
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)
Altri suggerimenti
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
Cambia i requisiti più del nostro team di marketing! Se vuoi che sia dinamico, dovrai ricorrere a uno sproc.