SQL Server - 在3列表上透视两列

时间:2018-02-18 01:49:11

标签: sql sql-server pivot

我有点陷入SQL枢轴, 我有一个像这样的3列表:

Name  Color  Date
TOM   BLUE   10-10-2018
MAT   RED    10-10-2018
TOM   BLUE   11-11-2018

我想要一个像这样的输出:

     10-10-2018  11-11-2018
 TOM  BLUE        BLUE
 MAT  RED         

有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

基于How to pivot dynamically with date as column的问题以及针对您案例的一些调整:

DECLARE @cols NVARCHAR (MAX);
SELECT @cols = COALESCE (@cols + ',[' + CONVERT(NVARCHAR, [DATE], 121) + ']', 
               '[' + CONVERT(NVARCHAR, [DATE], 121) + ']')
               FROM    (SELECT DISTINCT [DATE] FROM tablename) PV  
               ORDER BY [DATE]

DECLARE @query NVARCHAR(MAX)
SET @query = '           
              SELECT * FROM 
             (
                 SELECT * FROM tablename
             ) x
             PIVOT 
             (
                 MIN(Color)
                 FOR [DATE] IN (' + @cols + ')
            ) p      

            '     
EXEC SP_EXECUTESQL @query;

答案 1 :(得分:1)

你可以这样做:

firebase.database().ref('posts').remove();

SQLFiddle

如果要将NULL字段更改为空,请使用SELECT * FROM temp PIVOT( MAX(Color) FOR [Date] IN ([10-10-2018], [11-11-2018]) ) PIV ORDER BY Name DESC

喜欢这个

ISNULL(ColName, '')