SQL Pivot没有聚合

时间:2016-06-22 22:13:44

标签: sql sql-server pivot

我希望将数据集结果转出,但没有发生聚合。

Select StufferID from from #temp_Stuffers where SponsorID IN (111,222,333)

这将给我0 - 2个结果。我怎样才能使用pivot来实现它

Sponsor ID    StufferID1   StufferID2
111            S1           S2
222            S5
333

而不是

SponsorID     StufferID
111           S1
111           S2
222           S5

2 个答案:

答案 0 :(得分:1)

您需要使用outer join来获得所需的结果 - in将无法正常运行。首先,将where条件移至join。然后,您需要在pivot上建立一些字段,这使用row_number

select s.sponsorid, 
       max(case when t.rn = 1 then t.stufferid end) stufferid1,
       max(case when t.rn = 2 then t.stufferid end) stufferid2
from (select 111 as sponsorid union all select 222 union all select 333) s
    left join (
        select *, row_number() over 
                      (partition by sponsorid order by stufferid) rn 
        from #temp_Stuffers) t on s.sponsorid = t.sponsorid
group by s.sponsorid

如果您不知道潜在的填充值的最大数量,那么您还需要使用dynamic sql

答案 1 :(得分:1)

您可以使用别名将左连接作为自身使用,以查找每列的最小值和最大值。 您需要稍微修改它才能在SQL Server中使用,因为我正在使用Oracle。

SELECT TEMP_STUFFERS.SPONSORID, 
       MIN(TEMP_STUFFERS.STUFFERID)  AS STUFFERID1,
       MAX(TEMP_STUFFERS2.STUFFERID) AS STUFFERID2
  FROM TEMP_STUFFERS 
  LEFT JOIN TEMP_STUFFERS TEMP_STUFFERS2 
         ON TEMP_STUFFERS.SPONSORID  = TEMP_STUFFERS2.SPONSORID
        AND TEMP_STUFFERS.STUFFERID != TEMP_STUFFERS2.STUFFERID
 WHERE TEMP_STUFFERS.SPONSORID IN (111,222,333)
 GROUP BY TEMP_STUFFERS.SPONSORID
 ORDER BY TEMP_STUFFERS.SPONSORID;