简体   繁体   中英

Getting Count based on values of multiple rows of the same column

I am relatively new to database. Say that if I have table like below:

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

The expected output is :

PHeader BCount  TCount


p1          2    2

p2          0    1

BCount: is for the given PHeader and AHeader Value, if the IHeader values has all the values of (0,2 &3) then BCount value of PHeader is increased by 1 , Since for the p1 it has a1 & a4 with all the vaues of 0,2 & 3 as IHeader Values the BCount for p1 is given as 2

TCount: is for given given PHeader and AHeader value , if IHeader value has only 0 but not 2 or 3, then TCount for the given PHeader is increased by 1. Hence the TCount for p1 is given as 2.

Could you please give me tips in writing the query?

You can approach this using two aggregations. The inner one aggregates at the pheader , aheader level. This counts the values that you are interested in.

The outer one applies the logic that you've described to these summaries:

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;

EDIT:

The question is tagged MySQL. The following will work in both databases:

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;

Please check beloq sql query

SELECT 
PHeader ,
COUNT(*) as BCount  , --total 
SUM(CASE WHEN PHeader = 'p1' THEN 1 ELSE 0 END) as TCount  

FROM yourtablename group by PHeader

Hope this will give you some idea.

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