我有一个表可能在两列中的一列中列出搜索值,列B和/或列C.我想根据列A生成摘要,显示所选搜索值的次数(例如x) )出现在每个人的任一栏中。我想计算两列中的总数。
+--------+------+----+
| 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 |
+--------+-----------+
在上面的示例中,假设我的搜索值为x,我想计算列B和/或列C中每个人出现x的次数。我还想生成总计,并产生此输出:< / p>
Name B C
john 2 2
peter 2 0
amanda 5 3
total 9 5
我可以像这样单独为每个列执行此操作:
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";
然后我可以循环对每个输出进行单独的提取并将它们组合起来,但是我想知道是否有办法在两个列的mysql语句中进行检查和计数?
答案 0 :(得分:2)
如果您希望单独列出每列的总和,则可以使用以下(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
)
或者,如果您想要两个列的总和,那么您可以执行以下操作(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
)
答案 1 :(得分:1)
select...
case count (when A = 'x' then A else null) end,
case count (when B = 'x' then B else null) end
...
编辑: 哎呀,把计数遗漏了......
答案 2 :(得分:1)
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;
答案 3 :(得分:1)
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
答案 4 :(得分:1)
MySQL快捷方式,
SELECT Name,
SUM(B='x') TotalX,
SUM(C='x') TotalY
FROM TableName
GROUP BY Name