女士 SQL |如何使用非过滤数据查询过滤列(WHERE)

MS SQL | How to query a filtered column (WHERE) with non filtered data

我在解决 MS SQL 查询时遇到问题。 总之,查询应该将日期列作为两列,年份和月份,其他列的计数,列的总和以及过滤后的总和列。 我遇到的困难是添加过滤总和列。

一个样本数据,测试: 客户ID,1,2,3,4 ... 发票编号、1234551、1234552... 产品 ID、A、B、C... 日期、日期时间 收入,整数

customerID InvoiceID ProductID Date Income
1 1234551 A 01/01/2015 300
2 1234552 B 02/01/2016 300

我有一个解决方案,但我确信还有一个更简单的解决方案。

WITH CTE_1 AS
(
SELECT  Date,
        COUNT(DISTINCT Test.customerID) AS customers,
        COUNT(Test.InvoiceID) AS Invoices,
        COUNT(Test.ProductID) AS Products,
        Sum(Income) AS Total_Income,
        ISNULL((SELECT Sum(Income) AS Income_A FROM Test ts WHERE ProductID = 'A' AND ts.Date = Test.Date),0) AS Total_Income_A
FROM Test
GROUP BY Test.Date
)
SELECT YEAR(Date) AS Year,
       MONTH(Date) AS Month,
       Sum(customers) AS customers,
       Sum(Invoices) AS Invoices,
       Sum(Products) AS Products,
       Sum(Total_Income) AS Total_Income,
       Sum(Total_Income_A) AS Total_Income_A
FROM CTE_1
GROUP BY YEAR(Date), MONTH(Date)
ORDER BY YEAR(Date), MONTH(Date)

生产: 年,2015 年,2016 年…… 月、1、2、... 客户,国际 发票,国际 产品,国际 Total_Income, 整数 Total_Income_A, 整数

Year Month customers Invoices Products Total_Income Total_Income_A
2015 1 3 4 4 1600 600
2015 2 1 1 1 1200 0

谢谢! 尼尔

您可以直接应用条件聚合,例如

SELECT YEAR(Date) AS Year,
       MONTH(Date) AS Month,
       COUNT(DISTINCT customerID) AS customers,
       COUNT(DISTINCT InvoiceID) AS Invoices,
       COUNT(ProductID) AS Products,
       SUM(Income) AS Total_Income,
       ISNULL(SUM(CASE WHEN ProductID = 'A' THEN Income END),0) AS Total_Income_A
  FROM Test
 GROUP BY YEAR(Date), MONTH(Date)
 ORDER BY YEAR(Date), MONTH(Date)

Demo