[英]how to write aggregate conditional SQL query to get individual column counts and total counts by passing date arguments
I did some thing like this:我做了这样的事情:
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
I only get blank results.. also i'm passing date as input arguments for each select.我只得到空白结果......而且我将日期作为每个选择的输入参数传递。 column x exists in 4 different tables.
x 列存在于 4 个不同的表中。 All i have to do is show the count of x from each table for a particular date range.
我所要做的就是显示特定日期范围内每个表中 x 的计数。
You can use union all
and then conditional aggregation
as following:您可以使用
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;
Cheers!!干杯!!
Conditional Aggregation
can be used through JOIN
Clauses by x
columns which are common in name : 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
Conditions in WHERE
Clauses are assumed to be t1.y=1
, t2.z
, t3.a
, t4.b
respectively. WHERE
子句中的条件分别假设为t1.y=1
, t2.z
, t3.a
, t4.b
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.