在Pivot中如何消除重复项

时间:2019-02-27 12:08:56

标签: sql-server

旋转之前

 Year  | RainDays |
-------+----------+
 2012  |      112 |
 2013  |      116 |
 2014  |      111 |
 2015  |       80 |
 2016  |      110 |
 2017  |      102 |
 2018  |      80  |
 2019  |      110 |

旋转后

 2012 | 2013 | 2014 | 2015 | 2016 |  2017| 2018 | 2019 |  
 -----+------+------+------+------+------+------+------+
 112  |  116 |  111 |   80 |  110 |  102 |  0.0 |  0.0 |

如果第二次重复任何数字,则应将其设置为0.0

下面是数据透视的SQL

SELECT [1], [2], [3], [4], [5], [6], [7]    
FROM  
(
Select row_number () over(Order by [Year] asc) Rn,Raindays
from Rain
) AS SourceTable  
PIVOT  
(  
Max(Raindays)
FOR Rn IN ( [1], [2], [3], [4], [5], [6], [7])  
) AS PivotTable

2 个答案:

答案 0 :(得分:3)

您可以尝试使用ROW_NUMBER()跟随。

;with cte as
(
 select *, ROW_NUMBER() over(partition by raindays order by year) rn
 from @mytable
)
SELECT *
FROM  
(
 select Year, case when rn >1 then 0 else RainDays end as RainDays from cte 
)t 
PIVOT  
(  
max(RainDays)  
FOR Year IN ([2012], [2013], [2014], [2015], [2016],[2017],[2018],[2019])  
) AS PivotTable;  

Online Demo

输出

+------+------+------+------+------+------+------+------+
| 2012 | 2013 | 2014 | 2015 | 2016 | 2017 | 2018 | 2019 |
+------+------+------+------+------+------+------+------+
| 112  | 116  | 111  | 80   | 110  | 102  | 0    | 0    |
+------+------+------+------+------+------+------+------+

答案 1 :(得分:0)

您可以尝试

    create table #temptable ( name varchar(50), iid int )
    Go

    insert into #temptable ( name, iid )
    values ( '2012', 112 )
    ,( '2013', 215 )
    ,( '2014', 152 )
    ,( '2015', 112 )

    select * from #temptable


    ; with cte as (
    select row_number() over (partition by iid order by iid) as sl , * from #temptable)
    , ct as (
    select name, case when sl=1 then iid else 0 end as iid from cte)
    select * from (
    select name, iid from ct ) as d
    pivot ( max(iid) for name in ( [2012], [2013], [2014], [2015] ) ) as p

    go

    drop table #temptable