多行的条件SQL查询

时间:2016-01-16 18:08:58

标签: mysql sql

我试图找出哪些客户违约贷款。我想查询数据集以查找过去60天内未付款的客户的 User_id ,但不确定如何在SQL中实现此功能。

User_id    Due_Date                Loan_Amount    Paid_Amount
1          2012-04-04 16:14:12    500            40
1          2012-05-04 16:14:12    500            40
1          2012-06-04 16:14:12    500            0
1          2012-07-04 16:14:12    500            0
1          2012-08-04 16:14:12    500            0
2          2012-02-15 03:30:55    2030           100
2          2012-03-15 03:30:55    2030           100
2          2012-04-15 03:30:55    2030           100
3          2012-01-03 12:24:42    777            10
3          2012-02-03 12:24:42    777            0
3          2012-03-03 12:24:42    777            0
3          2012-04-03 12:24:42    777            0

在伪代码中(以粗体显示)看起来像这样,但我似乎无法在MySQL中实现它:

来自TABLE_NAME的SELECT User_id WHERE Loan_Amount> 0和[值Paid_Amount已超过60天]

期望的输出: 上述查询中的用户1和3将被退回,因为他们没有连续三​​个时段付款。

注意:Due_Date是时间戳

非常感谢任何想法!

2 个答案:

答案 0 :(得分:0)

您似乎可以使用DATEDIFF(date1, date1)功能获取逾期借款人列表。

SELECT DISTINCT
     user_id
FROM table_name n
     JOIN (SELECT user_id, max(due_date) maxDate FROM table_name GROUP BY user_id) t 
          ON n.user_id = t.user_id 
         AND n.due_date = t.maxDate
WHERE 
     loan_amount > 0
     AND paid_amount IS NULL
     AMD DATEDIFF(due_date, getdate()) > 60  

答案 1 :(得分:0)

我以前的查询错了,试试这个

select distinct t1.User_id
from TABLE_NAME t1
    inner join (
        select ts1.User_id, sum(ts1.Paid_Amount) as Paid_Amount_Total
        from TABLE_NAME ts1
        group by ts1.User_id
    ) t2
        on t1.User_id=t2.User_id and t1.Loan_Amount>t2.Paid_Amount_Total
)
where
    t1.Loan_Amount > 0
    and t1.User_id not in (
        select ts2.User_id
        from TABLE_NAME ts2
        where ts2.Due_Date>=DATE_SUB(NOW(), INTERVAL 60 DAY) and ts2.Paid_Amount>0
    )

t1,ts1,ts2 - 是TABLE_NAME的别名