Oracle - 计算CASE语句的结果

时间:2013-01-08 13:47:29

标签: sql oracle plsql count case

目标/背景

  • 我正在梳理一个工作订单系统,看看工人是否符合某些标准
    • (例如,如果他们不是第3阶段,第2阶段,甚至第1阶段)。
  • 这些“阶段”已由管理层定义。
  • 我想按报告的年份分组,然后是工艺,然后看看这些分组中有多少工作订单分别在3个“非阶段”中。

查询

select yearreported
, theleadcraft
, count(NotStage3)
, count(NotStage2)
, count(NotStage1)

from
(
    select extract(year from reportdate) as YearReported
    , Nvl(leadcraft, 'NONE') as TheLeadCraft
    , CASE when status not in ('CAN', 'CLOSE') then 1 else 0 END as NotStage3
    , CASE when status not in ('CAN', 'CLOSE', 'COMP') then 1 else 0 END as NotStage2
    , CASE when status not in ('CAN', 'CLOSE', 'COMP', 'WORKDONE') then 1 else 0  END as NotStage1
    from workorder
) query 

group by yearreported, theleadcraft;
;

问题/问题

  • 这似乎有效,但是对于notstage1,notstage2和notstage1的所有计数都是相同的,尽管在某些情况下查询并找到一些我知道不同的情况。
  • 这是实现我想要计算的案例陈述的正确方法吗?
  • 我应该使用DECODE()吗?

提前感谢您的帮助!

4 个答案:

答案 0 :(得分:9)

1和0都COUNT()相同 - 可能你想要SUM(),或COUNT()1或null。

答案 1 :(得分:0)

Count不计算NULL -s。试试这个:

, CASE when status not in ('CAN', 'CLOSE') then 1 END as NotStage3
, CASE when status not in ('CAN', 'CLOSE', 'COMP') then 1 END as NotStage2
, CASE when status not in ('CAN', 'CLOSE', 'COMP', 'WORKDONE') then 1 END as NotStage1

答案 2 :(得分:0)

您不应该使用decode

您编写查询的方式,您真的需要sum(),而不是count()

select yearreported, theleadcraft, sum(NotStage3), sum(NotStage2), sum(NotStage1)

函数count()在应用于列时具有误导性名称(在我看来)。它计算非NULL值的数量。由于“1”和“0”都是非NULL,因此它们会被计算在内。

答案 3 :(得分:0)

是的,您可以通过上述声明中的简单修改来实现

试试这个:

select yearreported
, theleadcraft
, count(decode (NotStage3, 1,1) )
, count(decode (NotStage2, 1,1) )
, count(decode (NotStage1, 1,1) )

from
(
    select extract(year from reportdate) as YearReported
    , Nvl(leadcraft, 'NONE') as TheLeadCraft
    , CASE when status not in ('CAN', 'CLOSE') then 1 else 0 END as NotStage3
    , CASE when status not in ('CAN', 'CLOSE', 'COMP') then 1 else 0 END as NotStage2
    , CASE when status not in ('CAN', 'CLOSE', 'COMP', 'WORKDONE') then 1 else 0  END as NotStage1
    from workorder
) query 

group by yearreported, theleadcraft;

的问候,

相关问题