如何使用PIVOT获得此功能?

时间:2018-01-12 05:26:24

标签: sql-server sql-server-2008 sql-server-2008-r2 pivot

我有一张这样的表: -

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

我怎么能得到这个?

1 个答案:

答案 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

存储日期