简体   繁体   中英

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. All i have to do is show the count of x from each table for a particular date range.

You can use union all and then conditional aggregation as following:

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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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