【问题标题】:Counting NULL values and Total Records计算 NULL 值和总记录
【发布时间】:2014-12-17 18:45:21
【问题描述】:

我使用一个公共表表达式和几个联合创建了以下查询,以实现可能更容易执行的操作。我有一个维度表“zc_order_status”,其中包含由“order_status”和“name”键控的数据。事实表“orders”包含以order_id为键的数据,包括order_status和其他各种数据。

关于事实表,我的目标是显示按 order_status 分组的 order_id 计数(对于所有 order_status,即使是那些未出现在事实表中的)。我还想显示 order_id 的计数,其中 order_status 为 NULL。最后,我想显示所有 order_id 的计数,而不考虑 order_status(类似于汇总)。

我能够使用此查询返回所需的值,但我对提高性能和简化流程感兴趣。

这是查询:

WITH sampledata
    (order_status, name)
AS
    (SELECT
         DISTINCT
         order_status
        ,name
     FROM
        zc_order_status
    )

SELECT
     zc.order_status
    ,zc.name
    ,COUNT(op.order_status) AS statuscount
FROM
    sampledata  AS zc
LEFT JOIN
    orders      AS op   ON zc.order_status = op.order_status
GROUP BY
     zc.name
    ,zc.order_status

UNION

SELECT
     999 AS order_status
    ,'UNKNOWN' AS name
    ,COUNT(order_id) AS statuscount
FROM
    orders
WHERE
    order_status IS NULL

UNION

SELECT
     9999 AS order_status
    ,'ALL RECORDS' AS name
    ,COUNT(order_id) AS statuscount
FROM
    orders

【问题讨论】:

  • 您使用的是哪个 dbms? sql server、mysql、oracle、postgres、newsqldbms?
  • 我正在使用 sql server。我应该在前面提到这一点。谢谢!

标签: sql count union common-table-expression


【解决方案1】:

我不能说你可能会看到多少性能差异,但试试这个:

with sampledata (order_status, name) as (
  select distinct 
      order_status
    , name
    from zc_order_status
  union all
  select 
      999 as order_status
    , 'unknown' as name
  )

  select 
      case when grouping (zc.order_status)=1 then 9999
           else zc.order_status 
           end as order_status
    , case when grouping (zc.name)=1 then 'all records'
           else zc.name 
           end as name
    , count(op.*) as statuscount
    from sampledata as zc
      left join orders as op
        on zc.order_status = coalesce(op.order_status, 999)
    group by grouping sets (
      (zc.order_status, zc.name)
      ,()
      )
    order by order_status;

【讨论】:

  • 感谢您提供替代方法。我用我的几个表测试了这个方法,它似乎在性能上是可比的。如果需要,有另一个选择总是很好的。也许我离一开始并不太远......
猜你喜欢
  • 2016-08-23
  • 2012-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多