SQL Server查询不同的行

时间:2014-05-13 21:17:17

标签: sql sql-server

如何查询不同的客户?这是我的表......

CustID  DATE    PRODUCT
=======================
1       Aug-31  Orange
1       Aug-31  Orange
3       Aug-31  Apple   
1       Sept-24 Apple
4       Sept-25 Orange

这就是我想要的。

# of New Customers            DATE
========================================
2                            Aug-31 
1                            Sept-25    

谢谢!

2 个答案:

答案 0 :(得分:6)

这有点棘手。您想要计算客户出现的第一个日期,然后进行汇总:

select mindate, count(*) as NumNew
from (select CustId, min(Date) as mindate
      from table t
      group by CustId
     ) c
group by mindate

答案 1 :(得分:1)

您可以使用简单的公用表表达式来查找第一次使用用户ID;

WITH cte AS (
  SELECT date, ROW_NUMBER() OVER (PARTITION BY custid ORDER BY date) rn
  FROM customers
)
SELECT COUNT(*)[# of New Customers], date FROM cte
WHERE rn=1
GROUP BY date
ORDER BY date

An SQLfiddle to test with