2015-05-20 39 views
2

我有一張表,其中包含每天和每位客戶的交易清單。我需要在6個月的週期內找到週日交易次數超過x次的客戶/交易日期。如果超過一週的x天,則返回

請注意,每個客戶每天可能有超過1筆交易,但只要他們在週日有1筆交易,那麼該週日就會計入6個月期間的週日計數。

這是我到目前爲止的代碼。我用的總和(transactionvalue)作爲天相結合可能的多筆交易的方法爲1次的記錄:

select customernumber,sum(transactionvalue),date from transactions 
where date between '2015-01-01' and '2015-06-01' 
and datename(weekday, date) = 'Sunday' 
group by customernumber,date 
having count(date) >= x 

然而,當我改變計數值,即「X」變大,記錄給定客戶變小。如果客戶在這段時間內有7個星期日,那麼我希望返回7條記錄,無論x是1還是7.只有當x大於7時,該客戶的所有交易纔會被退回。

下面是一些示例數據:

+-----------------+------------+--------------------+ 
| Customer Number | Date  | Transaction Amount | 
+-----------------+------------+--------------------+ 
| 1    | 17/05/2015 | 11.00    | 
| 2    | 17/05/2015 | 21.00    | 
| 2    | 17/05/2015 | 22.00    | 
| 3    | 17/05/2015 | 31.00    | 
| 3    | 17/05/2015 | 32.00    | 
| 3    | 17/05/2015 | 33.00    | 
| 1    | 24/05/2015 | 11.00    | 
| 2    | 24/05/2015 | 21.00    | 
| 3    | 24/05/2015 | 31.00    | 
| 2    | 31/05/2015 | 21.00    | 
+-----------------+------------+--------------------+ 

在這個例子中我期待具有以下返回如果x = 1:

+-----------------+------------+--------------------+ 
| Customer Number | Date  | Transaction Amount | 
+-----------------+------------+--------------------+ 
| 1    | 17/05/2015 | 11.00    | 
| 2    | 17/05/2015 | 43.00    | 
| 3    | 17/05/2015 | 96.00    | 
| 1    | 24/05/2015 | 11.00    | 
| 2    | 24/05/2015 | 21.00    | 
| 3    | 24/05/2015 | 31.00    | 
| 2    | 31/05/2015 | 21.00    | 
+-----------------+------------+--------------------+ 

但這返回如果x = 3:

+-----------------+------------+--------------------+ 
| Customer Number | Date  | Transaction Amount | 
+-----------------+------------+--------------------+ 
| 2    | 17/05/2015 | 43.00    | 
| 2    | 24/05/2015 | 21.00    | 
| 2    | 31/05/2015 | 21.00    | 
+-----------------+------------+--------------------+ 

感謝

+0

什麼你的意思做「如果客戶有7日在此段時間內,然後我希望返回7條記錄x是否爲1或7」?你能向我們展示你期望的一些行嗎? – Tim3880

+0

我的意思是如果客戶在給定的星期日有交易(無論那個星期天有多少),那麼就算是1星期天。如果他們有7個或更多的這樣的星期日,那麼我想讓那個返回。隨着x的增加,我希望看到記錄減少,因爲可能只有少數客戶在任何給定的星期日有超過7次的交易。 – Goolsy

回答

2

試試這個:

select customernumber, date, sum(transactionvalue) as transaction_amt 
from transactions 
where date >= '2015-01-01' and date < '2015-07-01' 
    and datename(weekday, date) = 'Sunday' 
and customernumber in (
    select customernumber 
    from transactions 
    where date >= '2015-01-01' and date < '2015-07-01' 
     and datename(weekday, date) = 'Sunday' 
    group by customernumber 
    having count(distinct date) >= 3 
)  
group by customernumber, date 

SQL Fiddle

相關問題