复杂的SQL Select语句

时间:2013-05-31 19:31:24

标签: mysql

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

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

  1. 如果表格中的任何一点存在给定字段“customer_number”
  2. 然后检查过去30天内是否有任何重复
  3. 然后输出按customer_number
  4. 分组的所有不同的customer_numbers
  5. 有计数,以便我可以看到项目被重复多少次。
  6. 因此,使用今天作为我们当前的日期说我在表格中有以下数据条目:

    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
    

    我一直在融化我的大脑,试图弄清楚在查询中如何甚至可以做任何帮助都会非常感激!

2 个答案:

答案 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

SQLFIDDLE