从四个表同时获取按日期分组的聚合值

时间:2015-11-10 03:12:10

标签: sql count group-by teradata outer-join

出于特定的下游原因,我试图从一个查询(Teradata)中的四个表中获取聚合数据。我已经能够通过编写子查询轻松完成此任务,但不幸的是,我还需要返回的数据按日期分组。每个字段都有一个timestamp属性(事务的时间),我希望返回一个包含列的表:Date,Count1,Count2,Count3,Count4。理想情况下,每个计数都具有该给定日期的交易总数,并且计数将根据表格而变化。

SELECT (SELECT COUNT(*) FROM TABLE1) AS COUNT1,
(SELECT COUNT(*) FROM TABLE2) AS COUNT2, 
(SELECT COUNT(*) FROM TABLE3) AS COUNT3, 
(SELECT COUNT(*) FROM TABLE4) AS COUNT4,

答案示例:

  1. 4/11/2015 5 2 7 22
  2. 4/12/2015 8 1 0 3
  3. 这样我可以从所有四个表中获取计数,但我想要SELECT CAST(Datestamp AS Date)并按此分组,同时获取每个日期的计数。 datestamp属性在每个表中,我该如何实现?我需要在这里做多个全外连接吗?我觉得加入可能没有必要,但我想把它搞定!感谢。

2 个答案:

答案 0 :(得分:0)

您可以使用union all。您也可以使用group byselect dte, max(t1cnt) as t1cnt, max(t2cnt) as t2cnt, max(t3cnt) as t3cnt, max(t4cnt) as t4cnt from ((select CAST(Datestamp AS Date) as dte, count(*) as t1cnt, 0 as t2cnt, 0 as t3cnt, 0 as t4cnt from table1 group by CAST(Datestamp AS Date) ) union all (select CAST(Datestamp AS Date) as dte, 0 as t1cnt, count(*) as t2cnt, 0 as t3cnt, 0 as t4cnt from table2 group by CAST(Datestamp AS Date) ) union all (select CAST(Datestamp AS Date) as dte, 0 as t1cnt, 0 as t2cnt, count(*) as t3cnt, 0 as t4cnt from table3 group by CAST(Datestamp AS Date) ) union all (select CAST(Datestamp AS Date) as dte, 0 as t1cnt, 0 as t2cnt, 0 as t3cnt, count(*) as t4cnt from table4 group by CAST(Datestamp AS Date) ) ) t group by dte order by dte;

执行此操作
  public async Task<List<TResource>> GetAllAsync(Expression<Func<TResource, bool>> filter = null,
            Func<IQueryable<TResource>, IOrderedQueryable<TResource>> orderBy = null)

答案 1 :(得分:0)

这里使用union all来组合所有表和条件聚合来计算每个(日期,表格)组合的行数:

select 
    myDate,
    count(case when n = 1 then 1 end) count1,
    count(case when n = 2 then 1 end) count2,
    count(case when n = 3 then 1 end) count3,
    count(case when n = 4 then 1 end) count4
from (
    select 1 n, cast(Datestamp as Date) myDate from table1
    union all select 2, cast(Datestamp as Date) myDate from table2
    union all select 3, cast(Datestamp as Date) myDate from table3
    union all select 4, cast(Datestamp as Date) myDate from table4
) t 
group by myDate