繁体   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