简体   繁体   中英

How to count per row by certain criteria

I have table employ with condition:

H=Hour, P=Present, S=Sick, A=Alpha

ID Name H1  H2 H3 H4 P  S   A
1  AAA   h  h  h  h  
2  BBB   s  s  h  h
3  CCC   a  h  h  h

how to get result like this:

ID Name H1  H2 H3 H4 P  S   A
1  AAA   h  h  h  h  4  0   0  
2  BBB   s  s  h  h  2  2   0
3  CCC   a  h  h  h  3  0   1

I have been 2 days browsing and browsing, try and try but I can't figure out how can I perform mysql query to solve that...

Thanks in advance and sorry for my bad English

I've made a few assumptions about what the data is in your post, and I think the following query may be what you've been trying to put together:

SELECT
id 'ID',
name 'Name',
h1 'H1',
h2 'H2',
h3 'H3',
h4 'H4',
SUM(if(h1='h',1,0)+if(h2='h',1,0)+if(h3='h',1,0)+if(h4='h',1,0)) as 'P',
SUM(if(h1='s',1,0)+if(h2='s',1,0)+if(h3='s',1,0)+if(h4='s',1,0)) as 'S', 
SUM(if(h1='a',1,0)+if(h2='a',1,0)+if(h3='a',1,0)+if(h4='a',1,0)) as 'A' 
FROM myTable
GROUP BY id

Feel free to ignore the column names, as that's only to match what you put in the post.

Basically, we're just checking the occurrence of each column's value in each field, providing a '1' if it's there, and a '0' if it isn't. We then add all of these results together to produce a multi-column count of that occurrence.

We then GROUP BY id to count each id's row only.

There may be a more elegant way of doing this, though.

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