计算NULL值和总记录

时间:2014-12-17 18:45:21

标签: sql count union common-table-expression

我使用公用表表达式和几个联合创建了以下查询,以实现可能更容易执行的操作。我有一个维度表" zc_order_status"包含由" order_status"键入的数据和"名称"。事实表"订单"包含order_id键入的数据,包括order_status和其他各种数据。

关于事实表,我的目标是显示按order_status分组的order_id计数(对于所有order_status,甚至是那些未出现在事实表中的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

1 个答案:

答案 0 :(得分:0)

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

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;