繁体   English   中英

如何编写聚合条件 SQL 查询以通过传递日期参数来获取单个列计数和总计数

[英]how to write aggregate conditional SQL query to get individual column counts and total counts by passing date arguments

我做了这样的事情:

with q1 as 
( 
  select x, count(*) as A from T1 where .. condition group by x
 ),
q2 as ( select x, count(*) AS B  from T2 where .. condition group by x),
q3 as ( select x, count(*) AS C from T3 where .. condition group by x),
Q4 AS ( select x, count(*) AS D from T4 where .. condition group by x)

SELECT Q1.X, Q1.A, Q2.B, Q3.C, Q4.D FROM Q1,Q2,Q3,Q4 

我只得到空白结果......而且我将日期作为每个选择的输入参数传递。 x 列存在于 4 个不同的表中。 我所要做的就是显示特定日期范围内每个表中 x 的计数。

您可以使用union all然后使用conditional aggregation ,如下所示:

Select x, 
       Coalesce(sum(case when tab ='Q1' then cnt end),0) As a,
       Coalesce(Sum(case when tab ='Q2' then cnt end),0) As b,
       Coalesce(Sum(case when tab ='Q3' then cnt end),0) As c,
       Coalesce(Sum(case when tab ='Q4' then cnt end),0) As d
From
     (Select 'Q1' as tab, x, count(*) cnt from t1 Where ... group by x
      Union all
      Select 'Q2' as tab, x, count(*) from t2 Where ... group by x
      Union all
      Select 'Q3' as tab, x, count(*) from t3 Where ... group by x
      Union all
      Select 'Q4' as tab, x, count(*) from t4  Where ... group by x)
Group by x;

干杯!!

Conditional Aggregation可以通过名称常见的x列的JOIN子句使用:

select t1.x, 
       count(case when t1.y=1 then 1 end ) as A,
       count(case when t2.z=0 then 1 end ) as B,
       count(case when t3.a=0 then 1 end ) as C,
       count(case when t4.b=0 then 1 end ) as D
  from t1
  join t2 on t2.x = t1.x
  join t3 on t3.x = t1.x
  join t4 on t4.x = t1.x
 group by t1.x

WHERE子句中的条件分别假设为t1.y=1 , t2.z , t3.a , t4.b

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM