gpt4 book ai didi

mysql:联合重用子查询

转载 作者:太空宇宙 更新时间:2023-11-03 11:22:32 26 4
gpt4 key购买 nike

有一张 table :

ID        City      

1 Toronto
2 Toronto
3 Toronto
4 Toronto
5 NY
6 NY

如何获取下表:

City    Total

NULL 6
Toronto 4
NY 2

我打算使用union:

(select city, count(*) as total from tbl group by city)
union
(select null, count(*) as total from tbl)

是否可以使用类似重用子查询的方法:

(select city, count(*) as total from tbl group by city) tmp
union
(select null, count(*) as tmp from tbl)

或者sql已经优化

(select city, count(*) as total from tbl group by city)
union
(select null, count(*) as total from tbl)

?

最佳答案

至少在 MySQL 5.5 和更新版本中,您可以使用 WITH ROLLUP无需额外查询即可获得分组元素总和的修饰符;

SELECT city, COUNT(*) AS total FROM tbl GROUP BY city WITH ROLLUP

city total
---------------
NY 2
Toronto 4
(null) 6

An SQLfiddle to test with .

关于mysql:联合重用子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58158407/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com