【问题标题】:How to use case in pivot如何在枢轴中使用案例
【发布时间】:2019-01-26 05:00:17
【问题描述】:

我想按部门和日期创建工作时间轴。 我有一个像 select department,sum(workinghours),date group by department,date. 然后我写了一个pivot sql

select * from(
     select department,sum(workinghours) as hours,date group by department,date
        )as RC
    PIVOT
    (
        sum(hours) for date 
    )as P

但这会返回很多空值。所以我将枢轴更新为

select * from(
         select department,sum(workinghours) as hours,date group by department,date
            )as RC
        PIVOT
        (
            (case when sum(hours) is null then 0 else sum(hours) end) for date 
        )as P

那么它有错误。 我不明白为什么,有人可以帮忙吗?谢谢。

【问题讨论】:

  • 样本数据和预期输出有助于正确引导,所以请分享样本数据和预期输出

标签: sql sql-server database plsql


【解决方案1】:

您需要将您的null 替换为sum 中的一些特定值。因为我已经替换了 0 而不是 null:

create table #t
(
Id int identity (1,1),
Department varchar (100),
WorkingHours int  ,
Date datetime
)

Insert into #t (Department,WorkingHours,Date)
Select '1','10',GETDATE ()-1

Insert into #t (Department,WorkingHours,Date)
Select '1','20',GETDATE ()-1
Insert into #t (Department,WorkingHours,Date)
Select '1',null,GETDATE ()

select * from #t

select * from(
         select department,sum(ISNULL(workinghours,0)) as hours,
         cast (Year(date) as varchar) date 
         from #t
         group by department,date
            )as RC
        PIVOT
        (
            sum(hours ) for date  IN ([2018])
        )as P

【讨论】:

    【解决方案2】:

    在 sum 内尝试以下大小写:

    select * from(
             select department,sum(workinghours) as hours,date group by department,date
                )as RC
            PIVOT
            (
                sum(case when hours is null then 0 else hours end) for date 
            )as P
    

    【讨论】:

      猜你喜欢
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-06
      • 1970-01-01
      • 2013-12-28
      • 2021-10-25
      • 1970-01-01
      相关资源
      最近更新 更多