计算SQL中case语句中的行

时间:2011-04-19 14:43:22

标签: sql count case

我试图在一个sql语句查询中获取今天,月到日,年初至今的行数(已输入)。但我不确定为什么它给了我所有三个相同的值。 这是我的sql语句。

select BU,
count(CASE when a.date_added = trunc(sysdate) then (part) else '0' end) 
as TodayQuotes,
count(CASE when a.date_added > last_day(add_months(sysdate,-1)) then (part) else '0'     end) 
as MTDQuotesValue,
COUNT(case when to_number(to_char(a.date_added,'yyyy'))='2011' then (part) else '0' end) 
as YTDRegularValue
from articles
group by BU;

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:2)

select BU,
       sum(CASE when a.date_added = trunc(sysdate) 
                then 1 
                else 0 
            end ) as TodayQuotes,
       sum(CASE when a.date_added > last_day(add_months(sysdate,-1)) 
                then 1 
                else 0 
            end) as MTDQuotesValue,
       sum(case when to_number(to_char(a.date_added,'yyyy'))='2011' 
                then 1 
                else 0 
            end) as YTDRegularValue
  from articles
 group by BU;

答案 1 :(得分:1)

"else '0'"表达式中删除CASE(隐含ELSE NULL}

COUNT计算所有NOT NULL个值,'0'NOT NULL,因此对COUNT有所贡献。