我有一张表,其中列出了每天和每位客户的交易清单。我需要找到在6个月内的星期日发生超过x次交易的客户/交易日期。
请注意,每位客户每天可能有超过1笔交易,但只要他们在星期日甚至有1笔交易,那么该周日就会计入6个月期间的星期日计数。
这是我到目前为止的代码。我使用sum(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 :(得分: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 强>