基准表:
date category amount
1/1/2012 ABC 1000.00
2/1/2012 DEF 500.00
2/1/2012 GHI 800.00
2/10/2012 DEF 700.00
3/1/2012 ABC 1100.00
动态SQL PIVOT:
create table temp
(
date datetime,
category varchar(3),
amount money
)
insert into temp values ('1/1/2012', 'ABC', 1000.00)
insert into temp values ('2/1/2012', 'DEF', 500.00)
insert into temp values ('2/1/2012', 'GHI', 800.00)
insert into temp values ('2/10/2012', 'DEF', 700.00)
insert into temp values ('3/1/2012', 'ABC', 1100.00)
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.category)
FROM temp c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT date, ' + @cols + ' from
(
select date
, amount
, category
from temp
) x
pivot
(
max(amount)
for category in (' + @cols + ')
) p '
execute(@query)
drop table temp
结果:
Date ABC DEF GHI
2012-01-01 00:00:00.000 1000.00 NULL NULL
2012-02-01 00:00:00.000 NULL 500.00 800.00
2012-02-10 00:00:00.000 NULL 700.00 NULL
2012-03-01 00:00:00.000 1100.00 NULL NULL
问题:我们如何继续使用上述动态SQL查询来使用CASE语句?
示例:对于ABC列
当值为1000.00那么' HIGH'
当值为500.00那么' MEDIUM'
同样适用于DEF专栏
当值为1000.00那么' HIGH'
当值为500.00那么' MEDIUM'
等等......对于所有列。 此外,如果将新列添加到基表..,CASE语句必须适用于该新列,而不对查询进行任何更改(我想可能需要循环条件)。 任何人都可以帮我解决如何修改上述查询(或)如何处理此要求。
答案 0 :(得分:1)
在生成数据透视Case statement
时使用column list
来处理别名。
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX),
@select_cols NVARCHAR(MAX);
SET @cols = Stuff((SELECT DISTINCT ',' + Quotename(c.category)
FROM temp c
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
SET @select_cols = Stuff((SELECT DISTINCT ',case when ' + Quotename(c.category)+ '= ''1000.00'' then ''High''
when ' + Quotename(c.category)+ '= ''500.00'' then ''Medium''
when ' + Quotename(c.category) + 'Is Null then ''Low''
else '+ Quotename(c.category) + ' end as '+ Quotename(c.category)
FROM temp c
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
SET @query = 'SELECT date, ' + @select_cols
+ ' from
(
select date
, convert(varchar(20),amount) Amount
, category
from temp
) x
pivot
(
max(amount)
for category in (' + @cols
+ ')
) p '
EXECUTE(@query)