PIVOT具有不同计算的多列

时间:2018-10-02 16:37:12

标签: sql pivot

我知道有人问过这个问题,但是我还没有找到适合我问题的答案

我有这个结构

Table structure

我需要着重记录数量,已批准,每天签名,以便看起来像这样:

Pivoted

如果您需要我提供其他任何信息,请告诉我 我感谢任何指导。谢谢

1 个答案:

答案 0 :(得分:0)

Date函数是特定于数据库的。下面给出了这个想法,并且可以在大多数数据库中使用:

select month(date) as mon, year(date) as yr, which,
       sum(case when day(date) = 1 then 1 else 0 end) as day_01,
       sum(case when day(date) = 2 then 1 else 0 end) as day_02,
       . . .
       sum(case when day(date) = 31 then 1 else 0 end) as day_31
from ((select date, 'reccount' as which, 1 as val from t
      ) union all
      (select date, 'approved' as which, approved as val from t
      ) union all
      (select date, 'signed' as which, signed as val from t
      ) 
     ) t
group by month(date), year(date), which
order by min(date), which ;