我正在尝试创建一个执行以下操作的SQL语句,但显然是失败了。
从视图中选择所有信息并根据以下条件对其进行过滤:
因此,使用今天作为我们当前的日期说我在表格中有以下数据条目:
customer_number, date
111111, 2013-01-01
111111, 2013-05-05
222222, 2013-01-07
222222, 2013-03-19
333333, 2013-05-15
333333, 2013-05-30
我希望我的SELECT语句返回以下内容:
customer_number, date, count
111111, 2013-01-01, 2
333333, 2013-05-15, 2
客户222222将不会显示,因为他没有出现在过去30天内。
就我已经试图解决这个问题而言。它只返回当月的数据。
SELECT *, COUNT(customer_number)
FROM red_flags
WHERE dealer_id = '75' AND date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()
GROUP BY customer_number
HAVING COUNT(customer_number) > 1
我一直在融化我的大脑,试图弄清楚在查询中如何甚至可以做任何帮助都会非常感激!
答案 0 :(得分:1)
这样的事情对你有用 - 它使用子查询来找出过去30天内被标记的客户。然后,它使用COUNT
获取总数,MIN
获取第一个日期。
SELECT customer_number, COUNT(1), MIN(date) minDate
FROM red_flags
WHERE customer_number IN (
SELECT customer_number
FROM red_flags
WHERE dealer_id = '75'
AND date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()
)
GROUP BY customer_number
如果您只关心具有多个记录的那些,您可以添加HAVING
子句。
顺便说一句,小心使用BETWEEN
和日期。我更喜欢明确并使用> =和< =来获得更多控制权。
编辑 - 也许是最简单的解决方案,使用带有CASE的COUNT:
SELECT customer_number, COUNT(1), MIN(date) minDate
FROM red_flags
GROUP BY customer_number
HAVING COUNT(CASE WHEN date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE() THEN 1 END) > 0
答案 1 :(得分:1)
以下是使用JOIN
的方法select r.customer_number, count(*) ct, min(date) minDate
from red_flags r
join (select distinct customer_number
from red_flags
where dealer_id = '75'
and date between CURDATE() - INTERVAL 30 DAY and CURDATE()) x
ON r.customer_number = x.customer_number
group by customer_number
HAVING ct > 1