如何在此表中使用pivot

时间:2014-02-17 08:39:05

标签: sql-server

Actual Table Structure
===================================
slno         ParnetID               ParnetName          Promotion    Marketer
1            SLM1010S               SKR.RAJASHEGARAN    2            43640
2            40049                  M.KANNAN            3            43640
3            40018                  M.PRABU             6            43640
4            SLM1010S               SKR.RAJASHEGARAN    2            43641
5            40042                  M.KANNAN            3            43641
6            40011                  M.PRABU             6            43641


i have my query :

WITH temp 
     AS (SELECT slno, 
                parentid, 
                parentname, 
                parentpromotionid, 
                marketerid, 
                (SELECT Count(*) 
                 FROM   parentmaster 
                 WHERE  t1.marketerid = marketerid 
                        AND t1.parentid = parentid 
                        AND t1.parentname = parentname 
                        AND slno <= t1.slno) AS RowNum 
         FROM   parentmaster AS t1) 
SELECT marketerid, 
       [2], 
       [6], 
       [3] 
FROM   temp 
       PIVOT ( Min(parentid) 
             FOR parentpromotionid IN ([2], 
                                       [6], 
                                       [3]) ) AS t 

但我想要这个表结构

MarketerID    2            6            3
43640         SLM1010S     40018        40049
43641         SLM1010S     40011        40042

3 个答案:

答案 0 :(得分:1)

这可能有助于你..

select marketer,[2],[3],[6] from
(
select Marketer,Promotion,ParnetID
from parentmaster 
) d pivot (min(ParnetID) for Promotion in ([2],[3],[6])) as pvt

答案 1 :(得分:0)

试试这个,

Declare @t table(slno int,ParnetID varchar(50),ParnetName varchar(50),Promotion int,Marketer int)
insert into @t
select 1,'SLM1010S','SKR.RAJASHEGARAN',    2,            43640 union all
select 2,'40049','M.KANNAN',            3,            43640 union all
select 3,'40018', 'M.PRABU',             6,            43640 union all
select 4,'SLM1010S',               'SKR.RAJASHEGARAN',    2,            43641 union all
select 5,'40042',                  'M.KANNAN',            3,            43641 union all
select 6,'40011',                  'M.PRABU',             6,            43641

select distinct a.Marketer,b.ParnetID ,c.ParnetID,d.ParnetID   from @t a
left join @t b on a.Marketer=b.Marketer and b.promotion=2
left join @t c on a.Marketer=c.Marketer and c.promotion=3
left join @t d on a.Marketer=d.Marketer and d.promotion=6

答案 2 :(得分:0)

select  Marketer, [0],[1],[2],[3],[4],[5],[6]
from  (
select Marketer,Promotion,ParnetID
from #t 
) d
pivot 
(
    MIN(ParnetID)
    FOR Promotion
    IN ([0],[1],[2],[3],[4],[5],[6])
) as TST