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

Posted

技术标签:

【中文标题】同时从四个表中获取按日期分组的聚合值【英文标题】:Getting Aggregate Values Grouped By Date from Four Tables Simultaneously 【发布时间】:2016-02-10 20:54:34 【问题描述】:

出于特定的下游原因,我试图在一个查询 (Teradata) 中从四个表中获取聚合数据。我已经能够通过编写子查询轻松地实现这一点,但不幸的是,我还需要返回的数据按日期分组。每个字段都有一个时间戳属性(交易时间),我希望返回一个包含以下列的表: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,

示例答案:

    4/11/2015 5 2 7 22 2015 年 4 月 12 日 8 1 0 3

这样我可以从所有四个表中获取计数,但我想 SELECT CAST(Datestamp AS Date) 并按此分组,同时获取每个单独日期的计数。 datestamp 属性在每个表中,我该如何做到这一点?我需要在这里做多个完整的外部连接吗?我觉得加入可能没有必要,但我想把它记下来!谢谢。

【问题讨论】:

【参考方案1】:

这是一种使用 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

【讨论】:

【参考方案2】:

您可以使用full outer join。您也可以使用union allgroup by 来执行此操作:

select 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;

【讨论】:

这个逻辑非常合理,但由于某种原因,它抱怨最后一个 union all 之后的语法。也许这只是一个 teradata 的东西,因为它看起来应该可以工作。谢谢,我假设 Null 和 0 的最大值会返回零?我问是因为我需要零来显示为零,并且给定的日期/表格会有很多零。 @marchocolate 。 . .我修好了。复制并粘贴碎屑。

以上是关于同时从四个表中获取按日期分组的聚合值的主要内容,如果未能解决你的问题,请参考以下文章

获取表中不同列的最新 NOT NULL 值,按公共列分组

按最新日期获取分组后的列

按日期间隔大于 X 的 DATETIME 获取数据、计数和分组

通过 linq 对实体查询进行分组,以通过加入表来获取具有最新时间戳的一条记录

Eloquent 获取按日期分组的最后一条记录

Laravel:如何从具有关系的 3 个表中获取数据