0

我正在尝试创建一个执行以下操作但显然失败的 SQL 语句。

从视图中选择所有信息并根据以下条件对其进行过滤:

  1. 如果给定字段“customer_number”存在于表中的任何位置
  2. 然后检查过去 30 天内的任何重复项
  3. 然后输出按 customer_number 分组的所有不同 customer_numbers
  4. 数一下,这样我就可以看到一个项目被重复了多少次。

因此,使用今天作为我们当前的日期说我的表中有以下数据条目:

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

我一直在试图弄清楚如何或是否可以在查询中做到这一点,任何帮助都将不胜感激!

4

2 回答 2

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日期。我更喜欢明确并使用 >= 和 <= 以获得更多控制权。


编辑——也许是最简单的解决方案,将 COUNT 与 CASE 一起使用:

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 
于 2013-05-31T19:40:09.653 回答
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

SQLFIDDLE

于 2013-05-31T19:56:42.817 回答