我对SQL有一点建议。我需要在两列中选择两个组(WHERE)。一些“喜欢”的工作:
SELECT COUNT(WHERE Draw=1) as D1, COUNT(WHERE Draw=2) as D2 FROM SampleData
示例数据表:
SampleData
--------------------
Id | Draw | Element
--------------------
1 | 1 | 13
2 | 1 | 15
3 | 1 | 22
4 | 1 | 36
5 | 1 | 45
6 | 2 | 11
7 | 2 | 15
8 | 2 | 22
并输出如下:
Output:
--------
D1 | D2
--------
5 | 3
答案 0 :(得分:0)
您可以为此使用CASE
表达式:
SELECT
COUNT(CASE WHEN Draw=1 THEN 1 END) as D1,
COUNT(CASE WHEN Draw=2 THEN 1 END) as D2
FROM SampleData
mysql还支持If()
,因此您也可以执行以下操作。请记住,这不能移植到其他RDBMS上,但是CASE
版本是:
SELECT
SUM(IF(Draw=1, 1, 0)) as D1,
SUM(IF(Draw=2, 1, 0)) as D2
FROM SampleData;
此外... mysql支持布尔表达式的数学运算,因此您可以在此处获得简洁:
SELECT SUM(Draw=1) as D1, Sum(Draw=2) as D2 FROM SampleData;
同样,尽管它不能像CASE
表达式那样移植到其他RDBMS中。
答案 1 :(得分:0)
也许是这样? (未试用)
SELECT COUNT(*) as D1 FROM SampleData WHERE Draw = 1 UNION SELECT COUNT(*) as D2 FROM SampleData WHERE Draw = 2