我有一个查询,我想计算3列s,s2和s3的值并使用Group By列的值?
到目前为止,我已经制作了这个db-fiddle
这会给我输出
1 - count 3
2 - count 3
4 - count 4
这几乎是正确的,但我也想包含正确的Where子句,因此计数将仅在season ='2018/2019'并且round = 34的地方。
所需的输出必须是:
1 - count 3
2 - count 2
4 - count 2
有什么主意如何编辑此查询,以便Where子句可以在计数值中起作用?
亲切的问候,
Arie
答案 0 :(得分:1)
您必须扩展联合查询以包括季节和舍入并在where子句中添加条件:
SELECT t.s, COUNT(*) as count FROM (
SELECT s, season, round FROM tablename UNION all
SELECT s2, season, round FROM tablename UNION all
SELECT s3, season, round FROM tablename
) as t
WHERE
t.s IN (
SELECT s FROM tablename
WHERE season = '2018/2019'
AND round = 34
AND s is not null
)
AND t.season = '2018/2019'
AND t.round = 34
AND t.s is not null
GROUP BY t.s
ORDER BY count DESC, t.s
请参见demo。
结果:
| s | count |
| --- | ----- |
| 1 | 3 |
| 2 | 2 |
| 4 | 2 |
答案 1 :(得分:0)
您应该过滤并集中每个表的行
SELECT t.s, COUNT(*) as count FROM (
SELECT s
FROM tablename
WHERE season = '2018/2019' and round = 34
UNION all
SELECT s2
FROM tablename
WHERE season = '2018/2019' and round = 34
UNION all
SELECT s3
FROM tablename
WHERE season = '2018/2019' and round = 34
) as t
GROUP BY t.s
ORDER BY count DESC