如何在SQL中将列作为一行

时间:2018-02-01 21:31:41

标签: sql-server sql-server-2012 pivot-table

如何将列QuotedReal和Rated作为'ActualStatus'列的值的一部分?

select
        EffectiveDate,
        ActualStatus,
        SUM(case when ActualStatus = 'Bound' then 1 
                 when ActualStatus = 'Declined' then 1
                 when ActualStatus = 'Quoted' then 1 
                 when ActualStatus = 'Not Taken Up' then 1
                 when ActualStatus = 'Indication' then 1
                 when ActualStatus = 'Submitted' then 1
                 when ActualStatus = 'Lost' then 1
                 when ActualStatus = 'Indicated' then 1             
        else 0 end) as CountActual,
        SUM(Quoted) as QuotedReal,
        SUM(Case when QuotedPremium is not null then 1 else 0 end) as Rated
from #Olegggg
group by EffectiveDate,
        ActualStatus

这就是我现在所拥有的:

enter image description here

但我需要这样的东西:

enter image description here

2 个答案:

答案 0 :(得分:2)

您可能需要使用UNION将3个记录集连接在一起..

select      EffectiveDate,
            ActualStatus,
            COUNT(*) as CountActual
from        #Olegggg
where       ActualStatus IN ('Bound','Declined',...'Indicated')
group by    EffectiveDate,
            ActualStatus

union all 
select      EffectiveDate,
            'Quoted Real',
            SUM(Quoted)
from        #Olegggg
group by    EffectiveDate

union all 
select      EffectiveDate,
            'Rated',
            COUNT(QuotedPremium)
from        #Olegggg
group by    EffectiveDate

答案 1 :(得分:1)

“JamieD”你的解决方案简单而正确,除了事实

1.ActualStatus不会在组中用于“Rated”和“QuotedReal”。它只应由EffectiveDate分组和汇总,以便每个日期有一行。

  1. 无需“全部联合”,因为我们没有任何重复数据可供选择。

    select      EffectiveDate,
                ActualStatus,
                COUNT(*) as CountActual
     from        #Olegggg
    where       ActualStatus IN ('Bound','Declined',...'Indicated')
    group by    EffectiveDate,
            ActualStatus
    union 
    select      EffectiveDate,
           'Quoted Real',
            SUM(Quoted)
    from        #Olegggg
    group by    EffectiveDate,
       //removed ActualStatus
    union 
      select      EffectiveDate,
                'Rated',
                 COUNT(QuotedPremium)
     from        #Olegggg
      group by    EffectiveDate,
        //removed ActualStatus