簡體   English   中英

SQL group by - 如何獲取上個月不存在的新記錄

[英]SQL group by - How to get new records that did not exist in any previous month

我有以下數據。

DECLARE @Table TABLE(
RequestID varchar(100)
, PersonID varchar(100)
, StartDate DATE
, EndDate DATE
, StatusType VARCHAR(150)
)

INSERT INTO @Table
SELECT '445566', 'Person2', '9/13/2022', '9/16/2022', 'TransactionStarted'
UNION ALL
SELECT '445566', 'Person2', '9/13/2022', '9/16/2022', 'TransactionEnded'
UNION ALL
SELECT '112233', 'Person2', '8/13/2022', '8/16/2022', 'TransactionStarted'
UNION ALL
SELECT '112233', 'Person2', '8/13/2022', '8/16/2022', 'TransactionEnded'
UNION ALL
SELECT '556677', 'Person1', '8/10/2022', '8/12/2022', 'TransactionStarted'
UNION ALL
SELECT '556677', 'Person1', '8/10/2022', '8/12/2022', 'TransactionEnded' 

我像這樣把數據拿出來,效果很好

SELECT COUNT(Distinct RequestID) TotalCountPerPerson,  DATENAME(mm, StartDate) [SRMonthName], MONTH(StartDate) [SRMonthNumber], YEAR(StartDate) [SRYear]
FROM @Table
GROUP BY  MONTH(StartDate), DATENAME(mm,StartDate), YEAR(StartDate)
ORDER BY  YEAR(StartDate), MONTH(StartDate)

但是,我需要一個額外的數據點,我無法弄清楚如何獲取。 在示例數據中,您可以看到“Person 2”和“Person1”都是 8 月份系統的“新”。 我需要一種將它們添加到查詢中的方法,以便我可以獲得每月和每年的總計數和新計數。 有人幫忙查詢嗎?

SELECT 2 TotalCountPerPerson, 2 NewThisMonth,   'August'[SRMonthName],  8 [SRMonthNumber],  2022 [SRYear]
UNION ALL
SELECT 1, 0 NewThisMonth,'September',   9,  2022

您可以使用自左連接,如下所示:

SELECT COUNT(Distinct T.PersonID) TotalCountPerPerson, 
       COUNT(Distinct CASE WHEN D.PersonID IS NULL THEN T.PersonID END) NewThisMonth,
       DATENAME(mm, T.StartDate) [SRMonthName], 
       MONTH(T.StartDate) [SRMonthNumber], YEAR(T.StartDate) [SRYear]
FROM @Table T LEFT JOIN @Table D
ON T.PersonID = D.personID AND T.StartDate > D.StartDate
GROUP BY MONTH(T.StartDate), DATENAME(mm,T.StartDate), YEAR(T.StartDate)
ORDER BY YEAR(T.StartDate), MONTH(T.StartDate)

查看演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM