您没有提供有关架构如何的任何信息,但我假设您有一个 Customer 表和一个 Transaction 表。考虑这个有 4 个客户和 12 个交易的例子。
客户
| id | name |
|----|----------|
| 1 | Google |
| 2 | Facebook |
| 3 | Hooli |
| 4 | Yahoo! |
交易
| id | transaction_date | customer_id |
|----|------------------|-------------|
| 1 | 2017-04-15 | 1 |
| 2 | 2017-06-24 | 1 |
| 3 | 2017-07-09 | 1 |
| 4 | 2017-07-24 | 1 |
| 5 | 2017-07-23 | 2 |
| 6 | 2017-07-22 | 2 |
| 7 | 2017-07-21 | 2 |
| 8 | 2017-07-24 | 2 |
| 9 | 2017-07-24 | 3 |
| 10 | 2017-07-23 | 4 |
| 11 | 2017-07-22 | 4 |
| 12 | 2017-07-21 | 4 |
要计算每个客户过去两个月的交易次数,一个简单的 group by 就可以完成这项工作:
select name, count(*) as number_of_transactions
from transactions t
inner join customers c on c.id = t.customer_id
where t.transaction_date > dateadd(month, -2, getdate())
group by c.name
这会产生
| name | number_of_transactions |
|----------|------------------------|
| Facebook | 4 |
| Google | 3 |
| Hooli | 1 |
| Yahoo! | 3 |
要仅检索交易日期等于今天的交易的客户,我们可以使用存在来检查这样的行是否存在。
select name, count(*) as number_of_transactions
from transactions t
inner join customers c on c.id = t.customer_id
where t.transaction_date > dateadd(month, -2, getdate())
and exists(select *
from transactions
where customer_id = t.customer_id
and transaction_date = convert(date, getdate()))
group by c.name
因此,如果事务表中的某行的 transaction_date 等于今天,并且 customer_id 等于来自主查询的 customer_id,则将其包含在结果中。运行该查询(鉴于今天是 7 月 24 日)给我们这个结果:
| name | number_of_transactions |
|----------|------------------------|
| Facebook | 4 |
| Google | 3 |
| Hooli | 1 |
Check out this sql fiddle http://sqlfiddle.com/#!6/710c94/13