首页 > 解决方案 > 如何在sql中根据月份将值的数量分组到列中

问题描述

我有一个数据集

Code Date 
123  21-Jan-2000 
234  23-Feb-1999 
123  19-Jan-2001

我想查询表以显示如下数据:

Code Total (All months) Jan Feb ... Dec 
123    2                 1   1
234    1                 0   1

我真的不知道如何开始。非常感谢任何提示或帮助。

标签: oracle-sqldeveloper

解决方案


你想用PIVOT. 从官方文档

select * from (
   select times_purchased, state_code
   from customers t
)
pivot 
(
   count(state_code)
   for state_code in ('NY','CT','NJ','FL','MO')
)
order by times_purchased

因此,在您的情况下,以下查询:

select * from (
    select code, datepart(month, date) as month
      from #data
) as data
pivot 
(
    count(code)
     for month in ('1','2','3','4','5','6','7','8','9','10','11','12')
)

推荐阅读