[英]Getting Count based on values of multiple rows of the same column
我對數據庫比較陌生。 假設我有如下表格:
PHeader AHeader IHeader
p1 a1 0
p1 a1 2
p1 a1 3
p1 a2 0
p1 a3 0
p1 a4 0
p1 a4 2
p1 a4 3
p2 a5 0
預期的輸出是:
PHeader BCount TCount
p1 2 2
p2 0 1
BCount:是給定的PHeader和AHeader值,如果IHeader值具有所有(0,2&3)值,則PHeader的BCount值將增加1,因為對於p1,它具有a1和a4且所有值0,2&3作為IHeader值p1的BCount給出為2
TCount:用於給定的給定PHeader和AHeader值,如果IHeader值僅具有0而沒有2或3,則給定PHeader的TCount增加1。因此,給定p1的TCount為2。
您能給我提示編寫查詢的技巧嗎?
您可以使用兩種聚合方法來實現。 內層聚集在pheader
( aheader
高級)級別。 這將計算您感興趣的值。
外部的將您描述的邏輯應用於這些摘要:
select pheader,
sum(ih_0 > 0 and ih_2 > 0 and ih_3 > 0) as bcount,
sum(ih_0 > 0 and (ih_2 = 0 or ih_3 = 0)) as tcount
from (select pheader, aheader,
sum(iheader = 0) as ih_0,
sum(iheader = 2) as ih_2,
sum(iheader = 3) as ih_3
from table t
group by pheader, aheader
) pa
group by pheader;
編輯:
問題被標記為MySQL。 以下內容將在兩個數據庫中均有效:
select pheader,
sum(case when ih_0 > 0 and ih_2 > 0 and ih_3 > 0 then 1 else 0 end) as bcount,
sum(case when ih_0 > 0 and (ih_2 = 0 or ih_3 = 0) then 1 else 0 end) as tcount
from (select pheader, aheader,
sum(case when iheader = 0 then 1 else 0 end) as ih_0,
sum(case when iheader = 2 then 1 else 0 end) as ih_2,
sum(case when iheader = 3 then 1 else 0 end) as ih_3
from table t
group by pheader, aheader
) pa
group by pheader;
請檢查beloq sql查詢
SELECT
PHeader ,
COUNT(*) as BCount , --total
SUM(CASE WHEN PHeader = 'p1' THEN 1 ELSE 0 END) as TCount
來自PHeader的yourtablename組
希望這會給您一些想法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.