2016-02-15 69 views
2

嗨我需要計數子類別= E的客戶數量由賣家(createdby)分組。一旦一位顧客被一個賣家計數,其他賣家都不應該能夠計算該顧客,儘管可能存在觀察。第一次計數的客戶出現

id customerID CreatedBy createdate subcategory 
1 1111111111 EVAJEN  2014-03-14 E           
2 1111111111 MICMAD  2014-04-15 E 
3 9999999999 MICMAD  2014-02-10 E` 

在這裏,因爲EVAJEN已經作出出售給客戶MICMAD不應該得到ID = 2的計數。現在我的代碼看起來像這樣,但我無法檢查客戶是否已經被計算在內。

sel createdby, cast(createdate as date) as date1, count(distinct customerID) 
from MyDatabase 
where subcategory='E' 
group by 1,2` 

謝謝

+0

請標記您的問題與您正在使用的數據庫。 –

回答

1

使用子查詢,以獲得第一日期和次數這一點。在大多數數據庫(包括Teradata的),你可以使用窗口函數來獲取第一排爲每一個客戶:

select createdby, cast(createdate as date) as date1, count(*) 
from (select t.*, 
      row_number() over (partition by customerId order by createddate asc) as seqnum 
     from MyDatabase t 
     where subcategory = 'E' 
    ) t 
where seqnum = 1 
group by createdby, cast(createdate as date) ; 
+0

不應該是row_number()結束(由customerId order by partitiondate ** ASC **分區)? – IDDQD

+0

@IDDQD。 。 。絕對。是的,你是對的。 –

+0

它的工作原理,感謝您的幫助 – IDDQD

0

您可以使用ROW_NUMBER讓每個客戶一行:

select createdby, cast(createdate as date) as date1, count(*) 
from 
(
    select * 
    from tab 
    where subcategory = 'E' 
    qualify row_number() -- 1st row per customer 
      over (partition by customerId 
       order by createddate) = 1 
    ) t 
group by 1,2;