SQL Server组数据透视表根据id

时间:2017-06-09 07:50:23

标签: sql sql-server pivot

我有一个名为'info'的表:

|InfoId   | OtherId | Year | InfoNo |
-------------------------------------
|1        | 1       | 2012 | abc    |
|2        | 1       | 2013 | def    |
|3        | 1       | 2014 | ghi    |

我想得到这个结果:

| OtherId   | 2012 | 2013 | 2014 |
---------------------------------
|   1       | abc  | def  | ghi  |

我尝试使用:

SELECT * 
FROM info
PIVOT (MAX(InfoNo) 
       FOR Year in ([2012],[2013],[2014])) AS pvt
       where OtherId= '1'

但相反,我得到了这个结果:

| OtherId   | 2012 | 2013 | 2014 |
---------------------------------
|   1       | abc  |       |     |
|   1       |      | def   |     |
|   1       |      |       | ghi |

如何根据'OtherId'将三行组分为一行?

修改

我将我的SQL更新为以下内容并设法获得我想要的结果:

SELECT 
OtherId,
MAX(case WHEN Year = '2012' THEN InvoiceNo ELSE NULL end) AS [2012],
MAX(case WHEN Year = '2013' THEN InvoiceNo ELSE NULL end) AS [2013],
MAX(case WHEN Year = '2014' THEN InvoiceNo ELSE NULL end) AS [2014]
FROM info

感谢所有人帮助我。

2 个答案:

答案 0 :(得分:0)

您需要按$numRows = $count['NumRows']; $sql = "INSERT INTO carbook (price, total_all) VALUES ('$numRows','$total' )"; 对结果进行分组,我做了一个快速测试,结果如下:

OtherId
Select * FROM info

InfoId      OtherId     Year        InfoNo
----------- ----------- ----------- ----------
1           1           2012        abc       
2           1           2013        edf       
3           1           2014        ghk

希望有助于你的事业。

答案 1 :(得分:0)

IF OBJECT_ID('Tempdb..#Temp') IS NOt NUll
Drop Table #Temp

;With cte(InfoId ,OtherId ,[Year],InfoNo)
AS
(
SELECT 1,1,'2012' , 'abc' Union all
SELECT 2,1,'2013' , 'def'   Union all
SELECT 3,1,'2014' , 'ghi'
)
SELECT * INTO #Temp FROM cte


DECLARE @dynamicCol nvarchar(max),@dynamicCol2 nvarchar(max),
        @Sql nvarchar(max)

SELECT @dynamicCol=STUFF((SELECT DISTINCT ', ' + QUOTENAME(Year)  FROM  #Temp
FOR XML PATH('')),1,1,'')

SELECT @dynamicCol2=STUFF((SELECT DISTINCT ', ' + 'MAX('+ QUOTENAME(Year) +' )' +'  AS '+ QUOTENAME(Year)  FROM  #Temp
FOR XML PATH('')),1,1,'')



SET @Sql= N' SELECT [OtherId] , '+ @dynamicCol2 +' From
             (
                SELECT InfoId ,OtherId ,[Year],InfoNo From
                #temp
              )AS Src
                PIVOT 
                    (
                    MAX([InfoNo]) For [Year] IN ('+@dynamicCol+')
                    )
            AS Pvt
            GROUP BY Pvt.OtherId
            '

PRINT @Sql

EXEC(@Sql)

输出

| OtherId   | 2012 | 2013 | 2014 |
---------------------------------
|   1       | abc  | def  | ghi  |