我有一张这样的表: -
DATE AREA
01-01-2018 AREA-1
02-01-2018 AREA-1
03-01-2018 AREA-2
我想要的结果应该是这样的: -
AREA 01-01-2018 02-01-2018 03-01-2018
AREA-1 YES YES NO
AREA-2 NO NO YES
我怎么能得到这个?
答案 0 :(得分:2)
以下是使用Application.Evaluate()
Pivot
更简单的方法
SELECT AREA,
COALESCE([01-01-2018], 'NO'),
COALESCE([02-01-2018], 'NO'),
COALESCE([03-01-2018], 'NO')
FROM (SELECT *,
'YES' AS t
FROM Yourtable)a
PIVOT(Max(t)
FOR DATE IN ([01-01-2018],[02-01-2018],[03-01-2018]) ) pv
动态版
SELECT AREA,
Max(CASE WHEN date = '01-01-2018' THEN 'YES' ELSE 'NO' END),
Max(CASE WHEN date = '02-01-2018' THEN 'YES' ELSE 'NO' END),
Max(CASE WHEN date = '03-01-2018' THEN 'YES' ELSE 'NO' END)
FROM Yourtable
GROUP BY AREA
注意:始终以DECLARE @col_list VARCHAR(max)='',
@select_list VARCHAR(max)='',
@sql VARCHAR(max)
SET @col_list = Stuff((SELECT DISTINCT ',' + Quotename(DATE)
FROM Yourtable
FOR xml path('')), 1, 1, '')
SET @select_list = Stuff((SELECT DISTINCT ',COALESCE(' + Quotename(DATE) + ',''NO'') as ' + Quotename(DATE)
FROM Yourtable
FOR xml path('')), 1, 1, '')
SET @sql = '
SELECT AREA,' + @select_list + '
FROM (SELECT *,
''YES'' AS t
FROM Yourtable)a
PIVOT(Max(t)
FOR DATE IN (' + @col_list + ') ) pv'
EXEC (@sql)
类型而不是Date