gpt4 book ai didi

sql - 一个 SQL 查询中的多个计数与分组

转载 作者:行者123 更新时间:2023-12-04 02:53:34 26 4
gpt4 key购买 nike

我想运行查询以获取按年和月分组的未解决事件和已关闭事件的计数,下面的查询在没有分组的情况下工作正常,但一旦我添加了组,它将无法工作!

SELECT (SELECT COUNT(*) AS Opened FROM Incidents) AS Total 
(SELECT COUNT(*) AS Solved FROM Incidents WHERE (MONTH(Closedate)=MONTH(Opendate))) AS Solved
GROUP BY YEAR(Incidents.Opendate)

最佳答案

您可以使用带有 CASE 表达式的单个 SELECT 语句

SELECT YEAR(Incidents.Opendate) AS [Year], 
MONTH(Incidents.Opendate) AS [Month],
COUNT(*) AS Total,
SUM(CASE WHEN MONTH(Closedate) = MONTH(Opendate) THEN 1 ELSE 0 END) AS Solved
FROM Incidents
GROUP BY YEAR(Incidents.Opendate), MONTH(Incidents.Opendate)

关于sql - 一个 SQL 查询中的多个计数与分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17130804/

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