每个月的T-SQL唯一记录数

时间:2015-05-29 14:49:41

标签: sql-server tsql

我正在努力获得每个月我们的客户群增长的数量。

EG。 “Josh”,“Tim”和“Dustin”在1月份使用了这项服务,因此1月份新的独特客户数量将达到3个。

二月,“Josh”,“Tim”和“Eve”将使用该服务。由于“Josh”和“Tim”以前使用过该服务,新的独特客户数量将为1。

依旧......

我想使用EXCEPT语句,但显然这并没有得到正确的结果。

SELECT COUNT(DISTINCT Name) as NewUniqueCustomers, convert(varchar(7), RegDate, 126)
FROM T
GROUP BY convert(varchar(7), RegDate, 126)
EXCEPT 

--This should excludie all customers which was included previously
SELECT COUNT(DISTINCT Name)as NewUniqueCustomers, convert(varchar(7), RegDate, 126)
FROM T 
WHERE convert(varchar(7), DATEADD(month,-1,RegDate) , 126)

GROUP BY convert(varchar(7), RegDate, 126)

http://sqlfiddle.com/#!3/73621

1 个答案:

答案 0 :(得分:4)

使用你的sqlfiddle这应该这样做。

with SortedData as
(
    select *
        , ROW_NUMBER() over(partition by Name order by RegDate) as RowNum
    from t
)

select dateadd(month, datediff(month, 0, RegDate), 0) 
    , COUNT(Name)
from SortedData sd
where sd.RowNum = 1
group by dateadd(month, datediff(month, 0, RegDate), 0) 

- 编辑 -

鉴于你对需要从两个表中提取工会的评论,为什么不这样呢?

with SortedData as
(
    select *
        , ROW_NUMBER() over(partition by Name order by RegDate) as RowNum
    from 
    (
        SELECT * FROM ProductionTable 
        UNION ALL 
        SELECT * FROM Archive.dbo.T
    )
    x
)