3

How do I query for distinct customers? Here's the table I have..

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

This is what I want.

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

Thanks!

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
JLYK
  • 391
  • 9
  • 22

2 Answers2

6

This is a bit tricky. You want to count the first date a customer appears and then do the aggregation:

select mindate, count(*) as NumNew
from (select CustId, min(Date) as mindate
      from table t
      group by CustId
     ) c
group by mindate
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1

You could use a simple common table expression to find the first time a user id is used;

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.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294