我有一个表,其中包含每天和每个客户的交易列表。我需要查找 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 个星期日,那么无论 x 是 1 还是 7,我都希望返回 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 |
+-----------------+------------+--------------------+
谢谢
最佳答案
试试这个:
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
关于sql - 如果一周中超过 x 天则返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30362272/