sql—在红移中执行不同汇总的更好方法?

6psbrbz9  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(353)

编写一个查询的最佳方法是在红移上对不同的离散时间范围内的不同计数进行汇总?
例如,如果您为各个组织的潜在客户收集了一些电话号码,并且希望了解每周、每月、每季度等创建了多少个不同的电话号码。。。最好的方法是什么?
这是我能想到的最好的办法:

SELECT
  organization,
  sum(weekly) as weekly,
  sum(monthly) as monthly,
  sum(quarterly) as quarterly,
  sum(yearly) as yearly
FROM (
    SELECT 
      organization,
      COUNT(DISTINCT phoneNumber) as weekly,
      null as monthly,
      null as quarterly,
      null as yearly
    FROM Lead
    WHERE createdAt >= current_date - interval '7 days'
    GROUP BY organization

      UNION ALL

    SELECT
      organization,
      null as weekly,
      COUNT(DISTINCT phoneNumber) as monthly,
      null as quarterly,
      null as yearly
    FROM Lead
    WHERE createdAt >= current_date - interval '1 month'
    GROUP BY organization

        UNION ALL

    SELECT
      organization,
      null as weekly,
      null as monthly,
      COUNT(DISTINCT phoneNumber) as quarterly,
      null as yearly
    FROM Lead
    WHERE createdAt >= current_date - interval '3 months'
    GROUP BY organization

        UNION ALL

    SELECT
      organization,
      null as weekly,
      null as monthly,
      null as quarterly,
      COUNT(DISTINCT phoneNumber) as yearly
    FROM Lead
    WHERE createdAt >= current_date - interval '1 year'
    GROUP BY organization
) GROUP BY organization

有什么方法可以让查询更快/更容易理解?

qco9c6ql

qco9c6ql1#

如果我理解正确,您可以使用条件聚合:

SELECT organization,
       COUNT(DISTINCT CASE WHEN created_at >= current_date - interval '7 day' THEN phoneNumber END) as weekly,
       COUNT(DISTINCT CASE WHEN created_at >= current_date - interval '1 month' THEN phoneNumber END) as monthly,
       COUNT(DISTINCT CASE WHEN created_at >= current_date - interval '3 month' THEN phoneNumber END) as quarterly,
       COUNT(DISTINCT CASE WHEN created_at >= current_date - interval '1 year' THEN phoneNumber END) as yearly
FROM Lead
WHERE createdAt >= current_date - interval '1 year'
GROUP BY organization;

相关问题