gpt4 book ai didi

SQL 选择来自同一列的多个计数

转载 作者:搜寻专家 更新时间:2023-10-30 23:33:03 29 4
gpt4 key购买 nike

我在 SQL 中有一个表,其中包含以下列:Status、CreateDateTime 和 Case Type

10 行数据的示例如下所示:

    Resolved-Withdrawn  2017-08-28 10:20:58.820 Termination Quote DE
Pending-Customer 2017-08-28 10:44:37.987 Termination Quote DE
Pending-Customer 2017-08-28 10:44:39.953 Termination Quote DE
Pending-Customer 2017-08-28 10:51:55.643 Termination Quote DE
Pending-Customer 2017-08-28 10:51:56.513 Termination Quote DE
Pending-Customer 2017-08-28 10:54:20.160 Termination Quote DE
Pending-Customer 2017-08-28 10:54:20.747 Termination Quote DE
Pending-Customer 2017-09-10 06:12:52.113 Termination Quote DE
Pending-Customer 2017-09-15 12:34:32.657 Termination Quote DE

我想实现以下目标:

    Status               Total_August     Total_September
-----------------------------------------------------
Resolved-Withdrawn 1 0
Pending-Customer 6 2

我将如何在 SQL 中创建此查询?

我最初的想法是这样的(这显然行不通),但也许它能让你作为一个没有经验的用户更好地理解我的思维过程。

    SELECT Status, COUNT(pxCreateDateTime) as Total_August, COUNT(pxCreateDateTime) as Total_September
FROM ContractMgtWork
WHERE MONTH(pxCreateDateTime) = 8 and YEAR(pxCreateDateTime) = 2017 AND
CaseType = 'Amortization Schedule DE'
GROUP BY Status

最佳答案

count 与许多其他聚合函数一样,跳过 null。您可以通过用任何您想要计算的 case 表达式来利用此属性:

SELECT   Status, 
COUNT(CASE WHEN MONTH(pxCreateDateTime) = 8 THEN 1 END) AS Total_August,
COUNT(CASE WHEN MONTH(pxCreateDateTime) = 9 THEN 1 END) AS Total_September
FROM ContractMgtWork
WHERE YEAR(pxCreateDateTime) = 2017 AND
CaseType = 'Amortization Schedule DE'
GROUP BY Status

关于SQL 选择来自同一列的多个计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46489825/

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