我对数据库比较陌生。 如果我有如下表格,请说:
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的所有vaues均为0,2& 3作为IHeader值p1的BCount为2
TCount:对于给定的给定PHeader和AHeader值,如果IHeader值仅为0而不是2或3,则给定PHeader的TCount增加1.因此,对于p1的TCount 给出为2。
请您给我写一下查询的提示?
答案 0 :(得分:0)
您可以使用两个聚合来解决此问题。内部聚合在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;
答案 1 :(得分:0)
请检查beloq sql查询
SELECT
PHeader ,
COUNT(*) as BCount , --total
SUM(CASE WHEN PHeader = 'p1' THEN 1 ELSE 0 END) as TCount
这 yourtablename PHeader小组
希望这会给你一些想法。