简体   繁体   English

如何按特定条件计算每行

[英]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...我已经浏览和浏览了 2 天,尝试并尝试,但我不知道如何执行 mysql 查询来解决该问题...

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.基本上,我们只是检查每个字段中每列值的出现情况,如果存在则提供“1”,如果不存在则提供“0”。 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.然后我们GROUP BY id只计算每个 id 的行。

There may be a more elegant way of doing this, though.不过,可能有一种更优雅的方式来做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM