[英]Mysql summarise all rows containing a value in one of two columns
I have a table that may have the search value in one of two columns, column B and/or column C. I want to produce a summary based on column A, showing how many times the selected search value (eg. x) appears in either column for each person. 我有一个表,该表可能在B列和/或C列两列之一中具有搜索值。我想根据A列产生一个摘要,显示所选搜索值(例如x)出现在多少次中每个人的任一列。 I want to count the totals in both columns.
我想计算两列的总数。
+--------+------+----+
| name | B | C |
+--------+------+----+
| john | x | z |
| john | x | x |
| john | y | x |
| peter | x | z |
| peter | x | z |
| amanda | x | x |
| amanda | x | x |
| amanda | x | x |
| amanda | x | y |
| amanda | x | y |
+--------+-----------+
In the above example, assuming my search value is x, I want to count how many times x appears for each person in column B and/or column C. I also want to produce grand totals, and produce this output: 在上面的示例中,假设我的搜索值为x,我想计算x在B列和/或C列中每个人出现的次数。我还想产生总计,并产生以下输出:
Name B C
john 2 2
peter 2 0
amanda 5 3
total 9 5
I can do it for each column separately like this: 我可以像这样分别为每列做到这一点:
SELECT name, COUNT(*) as count FROM table
WHERE A = 'x'
GROUP BY name
ORDER BY count DESC";
SELECT name, COUNT(*) as count FROM table
WHERE B = 'x'
GROUP BY name
ORDER BY count DESC";
I can then loop around doing separate fetches on the output from each and combine them, but I want to know if there is a way to do the check and counting in one mysql statement for the two columns please? 然后,我可以循环对每个输出进行单独的提取,并将它们组合在一起,但是我想知道是否有一种方法可以对两列的一个mysql语句进行检查和计数?
If you want the sum of each column separately then you could use the following ( SQL Fiddle ): 如果您想分别获取每一列的总和,则可以使用以下内容( SQL Fiddle ):
(
SELECT MTA.Name, Sum(MTA.B = 'x') AS BSum, Sum(MTA.C = 'x') AS CSum
FROM MyTable MTA
GROUP BY MTA.Name
)
UNION
(
SELECT 'Total' AS name, Sum(MTB.B = 'x') AS BSum, Sum(MTB.C = 'x') AS CSum
FROM MyTable AS MTB
)
Or if you want the sum of both columns combined then you could do something like the following ( SQL Fiddle ): 或者,如果您希望将两列的总和合并,则可以执行以下操作( SQL Fiddle ):
(
SELECT MTA.Name, Sum(MTA.B = 'x') + Sum(MTA.C = 'x') AS PersonTotal
FROM MyTable MTA
GROUP BY MTA.Name
)
UNION
(
SELECT 'Total' AS name, Sum(MTB.B = 'x') + Sum(MTB.C = 'x') AS PersonTotal
FROM MyTable AS MTB
)
select...
case count (when A = 'x' then A else null) end,
case count (when B = 'x' then B else null) end
...
EDIT: Oop, left out the count... 编辑:糟糕,不包括在内...
SELECT name,
COUNT(CASE WHEN B='x' THEN 1 ELSE 0 END) as B,
COUNT(CASE WHEN C='x' THEN 1 ELSE 0 END) as C FROM table
GROUP BY name;
SELECT name, sum(if(B='x',1,0)) as c1, sum(if(C='x',1,0)) as c2FROM table
WHERE A = 'x'
GROUP BY name
ORDER BY c1 desc, c2 desc
MySQL Shortcut, MySQL捷径,
SELECT Name,
SUM(B='x') TotalX,
SUM(C='x') TotalY
FROM TableName
GROUP BY Name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.