【问题标题】:Counting lines in case statement in SQL在 SQL 中的 case 语句中计算行数
【发布时间】:2011-04-19 14:43:22
【问题描述】:

我正在尝试在一个 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;

任何帮助将不胜感激

【问题讨论】:

  • 为什么先转换to_char,然后转换to_number,最后比较成字符串('2011')?

标签: sql count case


【解决方案1】:
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;

【讨论】:

    【解决方案2】:

    CASE 表达式中删除"else '0'"(有一个隐含的ELSE NULL

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

    【讨论】:

      猜你喜欢
      • 2022-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-02
      • 1970-01-01
      • 2018-01-29
      • 2014-12-05
      • 1970-01-01
      相关资源
      最近更新 更多