我对MySQL的这个查询有问题。
如果试过这个版本:
mysql> SELECT
COUNT(*),
myCode,
myState
FROM
`tbl_2016`
WHERE
`myCode` LIKE '%XI10-2-020012%'
GROUP BY
`myState`;
输出结果为:
+----------+---------------+--------------------------------+
| COUNT(*) | myCode | myState |
+----------+---------------+--------------------------------+
| 5 | XI10-2-020012 | NULL |
| 4 | XI10-2-020012 | ACTIVE |
| 1 | XI10-2-020012 | NOT ACTIVE |
+----------+---------------+--------------------------------+
2 rows in set
但如果尝试使用 CASE WHEN 语法
的其他版本mysql> SELECT
myCode,
COUNT(
CASE
WHEN myState IN (
'Active'
) THEN
1
ELSE
0
END
) AS `Active`,
COUNT(
CASE
WHEN myState IN (
'Not Active'
) THEN
1
ELSE
0
END
) AS `Not Active`
FROM
`tbl_2016`
WHERE
`myCode` LIKE '%XI10-2-020012%'
GROUP BY
`myState`;
输出与第一个版本不同:
+---------------+--------+------------+
| myCode | Active | Not Active |
+---------------+--------+------------+
| XI10-2-020012 | 4 | 4 |
+---------------+--------+------------+
1 row in set
如何解决这个问题?
你能帮助我吗?
提前感谢您,我的代码如下。
答案 0 :(得分:1)
在第二个版本中使用SUM而不是COUNT