我正在尝试实现Pivot SQL

时间:2017-06-08 09:17:42

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

这是我第一次尝试进行调整,但即使在线提供所有信息,我仍然没用:(

我有这张桌子。

+-----+-----------------+------------+
| ID  | ChecklistItemID | Attachment |
| 327 | 912             | 611        |
| 328 | 912             | 612        |
+-----+-----------------+------------+

和这张表

+-----+----------+
| ID  | FileName |
| 611 | 2.jpg    |
| 612 | 3.jpg    |
+-----+----------+

我希望我的输出像这样

+-----------------+-------+-------+
| ChecklistItemID | File1 | File2 |
| 912             | 2.jpg | 3.jpg |
+-----------------+-------+-------+

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

这似乎可以解决问题。我已经把它打开了,因为你还没有说你是为所有数据做了这个还是只是一个特定的清单。

诀窍是使用ROW_NUMBER()获取File列的已知名称:

declare @t1 table (ID int not null,ChecklistItemID int not null,Attachment int not null)
insert into @t1(ID,ChecklistItemID,Attachment) values
(327,912,611),
(328,912,612)

declare @t2 table (ID int not null, FileName varchar(9) not null)
insert into @t2(ID,FileName) values
(611,'2.jpg'),
(612,'3.jpg')

;With Ordered as (
    select
        t1.ChecklistItemID,
        FileName,
        'File' + CONVERT(varchar(5),ROW_NUMBER() OVER (PARTITION BY t1.ChecklistItemID
                                     ORDER BY t2.ID)) as FileTitle
    from
        @t1 t1
            inner join
        @t2 t2
            on
                t1.Attachment = t2.ID
)
select
    *
from
    Ordered
        pivot (MIN(FileName) for FileTitle in (File1,File2,File3)) u

结果:

ChecklistItemID File1     File2     File3
--------------- --------- --------- ---------
912             2.jpg     3.jpg     NULL

答案 1 :(得分:0)

IF OBJECT_ID('Tempdb..#Temp') IS NOT NULL
Drop table #Temp

Declare @Tab1 TABLE ( ID INT, ChecklistItemID INT , Attachment INT)
Insert into @Tab1
SELECT 327 , 912, 611 UNION ALL        
SELECT 328 , 912, 612        

Declare @Tab2 TABLE (ID INT,FileName Varchar(10))
INSERT INTO @Tab2
SELECT  611 , '2.jpg' Union all
SELECT  612 , '3.jpg'    

SELECT ChecklistItemID,[FileName] INTO #Temp FROM @Tab1 t1
INNER JOIN @Tab2 t2
ON t1.Attachment=t2.ID


DECLARE @COulmn nvarchar(max),
        @query nvarchar(max)
SELECT @COulmn= STUFF((SELECT ', '+'File'+CAST( ROW_NUMBER()OVER(PARTITION BY ChecklistItemID ORDER BY ChecklistItemID) AS Varchar(5))
FROM #Temp For XML PATH ('')),1,1,'') 


SET @query = N'SELECT ChecklistItemID,' + @COulmn + N' from 
             (
                SELECT *,''File''+ CAST(ROW_NUMBER()OVER(PARTITION BY ChecklistItemID ORDER BY ChecklistItemID) AS Varchar(5)) As FileColumn
                FROM #Temp
            ) Src
            PIVOT 
            (
                MAX([FileName])
                FOR FileColumn in (' + @COulmn + N')
            ) pvt '

EXEC sp_executesql @query;

输出

ChecklistItemID File1   File2
-----------------------------
912             2.jpg   3.jpg