簡體   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