如何获取记录数的总和(来自先前的查询)

时间:2017-04-26 15:27:16

标签: sql amazon-redshift

我对相对复杂的SQL很新,可以在问题上使用一些帮助。我有一个问题:

select
  case 
    when group_id = 'ABC Acme' then 'ABC'
    when group_id like 'Premium%' then 'PREM'
    when group_id like '%Marvel%' then 'MRV'
    else  NULL
  end client, 
  load_date, report_date, count(*) as record_count
from tablename
group by client, load_date, report_date
order by client, load_date;

返回以下内容:

client  load_date   report_date record_count
ABC     4/1/2016    2/28/2016   16108
PREM    4/19/2016   3/31/2017   5348
MRV     4/19/2016   3/31/2017   8335

如果可能,我想获得record_count(或29791)的总和。理想情况下,将最后一行添加到具有此总计的上述结果中会很棒。我尝试了以下查询但它没有用...

select
  case 
    when group_id = 'ABC Studios' then 'ABC'
    when group_id like 'Premium%' then 'PREM'
    when group_id like '%Marvel%' then 'MRV'
    else NULL
  end client, 
  load_date, report_date, count (*)
from tablename
  group by client, load_date, report_date
  union all
select 'SUM', count(*)
from tablename;

我收到以下错误:

An error occurred when executing the SQL command:
--get summary ttl of counts by load_date for each client
select
case wh...
[Amazon](500310) Invalid operation: each UNION query must have the same number of columns;
Execution time: 0s
1 statement failed.

3 个答案:

答案 0 :(得分:0)

当您将union个记录集放在一起时,它们需要具有相同数量的列。现在,您的第一个查询有4列,第二个查询只有2列。只需为load_date选择null,在第二个查询中选择report_date(无论如何,这些字段对于总计都没有意义。)

select
  case 
    when group_id = 'ABC Studios' then 'ABC'
    when group_id like 'Premium%' then 'PREM'
    when group_id like '%Marvel%' then 'MRV'
  else
    NULL
  end client, load_date, report_date, count (*), 1 priority
  from tablename
  group by client, load_date, report_date

  union all

  select 'SUM', null, null, count(*), 2 priority
  from tablename
  order by priority;

答案 1 :(得分:0)

大多数数据库支持grouping setsrollup,这无疑简化了这一点。

为了可维护性和一致性,我更喜欢使用CTE:

with t as (
      select (case when group_id = 'ABC Acme' then 'ABC'
                   when group_id like 'Premium%' then 'PREM'
                   when group_id like '%Marvel%' then 'MRV'
              end) as client, 
             load_date, report_date, count(*) as record_count
      from tablename
      group by client, load_date, report_date
     )
select client, load_date, report_date, record_count
from ((select t.*, 1 as priority
       from t
      ) union all
      (select 'SUM', NULL, NULL, sum(record_count), 2
       from t
      )
     ) t
order by priority, client, load_date;

注意:

  • 通过在CTE中设置任何潜在的过滤条件或计算,可以确保一致性。
  • 实际上,数据库按顺序返回UNION ALL的行。但这不能保证。显式使用priority列可确保数据的顺序正确。
  • 添加额外的子集合非常容易。
  • grouping sets是首选。

答案 2 :(得分:0)

您可以将总记录的额外列添加为

declare @ttl int;
Set @ttl = (Select Count(*) from tablename)
select
  case 
    when group_id = 'ABC Studios' then 'ABC'
    when group_id like 'Premium%' then 'PREM'
    when group_id like '%Marvel%' then 'MRV'
  else
    NULL
  end client, load_date, report_date, count (*), @ttl AS Sum
  from tablename
  group by client, load_date, report_date