列出所有月份的总数,无论是否为null

时间:2017-12-14 14:28:54

标签: sql oracle count

我有一个非常小的SQL表,列出了参加的课程和出席日期。我可以使用下面的代码计算每个月的与会者

select to_char(DATE_ATTENDED,'YYYY/MM'),
COUNT (*)
FROM TRAINING_COURSE_ATTENDED
WHERE COURSE_ATTENDED = 'Fire Safety'
GROUP BY to_char(DATE_ATTENDED,'YYYY/MM')
ORDER BY to_char(DATE_ATTENDED,'YYYY/MM')

这将返回具有与会者的每个月的预期列表。但是我想将其列为

January 2
February 0
March 5

如何显示计数结果和空值?我的表非常基本

1234    01-JAN-15   Fire Safety
108 01-JAN-15   Fire Safety
1443    02-DEC-15   Healthcare
1388    03-FEB-15   Emergency
1355    06-MAR-15   Fire Safety
1322    09-SEP-15   Fire Safety
1234    11-DEC-15   Fire Safety

我只需要显示每个月和仅限消防安全的参与者。没有使用SQL开发人员一段时间,所以任何帮助赞赏。

4 个答案:

答案 0 :(得分:0)

您需要一个日历表来选择要显示的句点。简化的代码如下所示:

select to_char(c.Date_dt,'YYYY/MM')
, COUNT (*)

FROM calendar as c
left join TRAINING_COURSE_ATTENDED as tca
 on tca.DATE_ATTENDED = c.Date_dt

WHERE tca.COURSE_ATTENDED = 'Fire Safety'
    and c.Date_dt between [period_start_dt] and [period_end_dt]
GROUP BY to_char(c.Date_dt,'YYYY/MM')
ORDER BY to_char(c.Date_dt,'YYYY/MM')

答案 1 :(得分:0)

试试这个:

SELECT Trunc(date_attended, 'MM') Month, 
       Sum(CASE 
             WHEN course_attended = 'Fire Safety' THEN 1 
             ELSE 0 
           END) Fire_Safety 
FROM   training_course_attended 
GROUP  BY Trunc(date_attended, 'MM') 
ORDER  BY Trunc(date_attended, 'MM') 

答案 2 :(得分:0)

您可以使用0计数创建自己的所需年份,并使用查询,如下所示。

Select yrmth,sum(counter) from
(
    select to_char(date_attended,'YYYYMM') yrmth,
           COUNT (1) counter
    From TRAINING_COURSE_ATTENDED Where COURSE_ATTENDED = 'Fire Safety'
    Group By Y to_char(date_attended,'YYYYMM')
    Union All
    Select To_Char(2015||Lpad(Rownum,2,0)),0 from Dual Connect By Rownum <= 12
)
group by yrmth
order by 1

如果您想要显示多年,只需将第二个查询更改为

即可
Select To_Char(Year||Lpad(Month,2,0)) , 0 
From 
(select Rownum Month from  Dual Connect By Rownum <= 12),
(select 2015+Rownum-1 Year from  Dual Connect By Rownum <= 3)

答案 3 :(得分:0)

另一种内联生成日历表的方法:

with calendar (month_start, month_end) as
     ( select add_months(date '2014-12-01', rownum)
            , add_months(date '2014-12-01', rownum +1) - interval '1' second
       from   dual
       connect by rownum <= 12 )
select to_char(c.month_start,'YYYY/MM') as course_month
     , count(tca.course_attended) as attended
from   calendar c
       left join training_course_attended tca
            on   tca.date_attended between c.month_start and c.month_end
            and  tca.course_attended = 'Fire Safety'
group by to_char(c.month_start,'YYYY/MM')
order by 1;

(您也可以只在日历表中开始月份,然后加入trunc(tca.date_attended,'MONTH') = c.month_start,但如果tca.date_attended上的索引或分区可能效率较低。)