如何编写SQL查询来获取此输出?

时间:2011-11-15 13:04:51

标签: php mysql

我的数据库表包含以下字段:

id, loan_no, installment, status

有贷款信息,如

如果贷款有24个分期付款,那么将有24行包含相同的loan_no和分期付款状态,这些行是付款或非分期付款。

所以我想获得loan_no的所有分期付款状态=已付款。

是否可以编写一个查询来获得结果?

6 个答案:

答案 0 :(得分:1)

试试这个:

SELECT loan_no FROM your_table
WHERE loan_no NOT IN
  SELECT DISTINCT loan_no FROM your_table
  WHERE status = 'unpaid')
GROUP BY loan_no

答案 1 :(得分:1)

这样的东西
select distinct
        i.loan_no,
        i.status
    from
        info as i
        left outer join info as i2
            on i.loan_no = i2.loan_no and i2.status = 'unpaid'
    where
        i.status = 'paid'
        and
        i2.loan_no is null
;

答案 2 :(得分:0)

SELECT DISTINCT loan_no FROM loan
WHERE loan_no NOT IN (SELECT DISTINCT loan_no FROM loan WHERE status = 'unpaid')

答案 3 :(得分:0)

SELECT loan_no FROM table where status = "paid" group by loan_no;

答案 4 :(得分:0)

SELECT A.loan_no FROM (
    SELECT loan_no, COUNT(status) AS installments
    WHERE status = 'paid' 
    GROUP BY loan_no, status
) AS A
WHERE A.installments = 24

所有贷款总是有24笔付款?如果你想为已经支付了所有24笔款项的所有贷款提取loan_no,那么上述内容就可以了。

答案 5 :(得分:0)

SELECT loan_no FROM YOUR_TABLE
WHERE id NOT IN (SELECT id FROM YOUR_TABLE WHERE status = 'unpaid') GROUP BY loan_no