如何使用 SQL Server Management Studio 形成查询以返回每个不同项目的多个计数

问题描述 投票:0回答:1

这是我的询问。我知道它不正确,特别是计数语法。

SELECT DISTINCT
    product AS Type, 
    COUNT(DISTINCT c.id) AS [Total Count],
    COUNT(DISTINCT c.id = c.qDate >= '2023-06-06 00:00:00.0000000') AS [Count < One Year], 
    COUNT(DISTINCT c.id = c.qDate >= '2022-06-06 00:00:00.0000000') AS [Count < Two Year] 
FROM 
    [table1] t1
JOIN
    [table2] t2 ON t1.ID = t2.ID
JOIN 
    [table3] t3 ON t2.mb = t3.mb
WHERE 
    status IN ('P', NULL) 
GROUP BY 
    Product, c.qDate
ORDER BY
    Product

我希望查询返回的内容示例:

Type        TotalCount     Count < 1 Yr    Count < 2 Yrs
--------------------------------------------------------
Van          10000           3000            7000
Car          50000          30000           70000
Truck         5000            200             500 
sql count
1个回答
0
投票

COUNT函数用于对非空值进行计数,因此需要在COUNT函数中使用CASE语句来实现条件计数。尝试:

SELECT 
    t1.Product AS Type,
    COUNT(DISTINCT c.id) AS [Total Count],
    COUNT(DISTINCT CASE WHEN c.qDate >= '2023-06-06 00:00:00.0000000' THEN c.id END) AS [Count < One Year], 
    COUNT(DISTINCT CASE WHEN c.qDate >= '2022-06-06 00:00:00.0000000' AND c.qDate < '2023-06-06 00:00:00.0000000' THEN c.id END) AS [Count < Two Year] 
FROM 
    [table1] t1
JOIN
    [table2] t2 ON t1.ID = t2.ID
JOIN 
    [table3] t3 ON t2.mb = t3.mb
WHERE 
    t1.status IN ('P', NULL) 
GROUP BY 
    t1.Product
ORDER BY
    t1.Product;
© www.soinside.com 2019 - 2024. All rights reserved.