我有一个名为loan_emi的表。我想选择最后一个emi支付日期,最后一个emi日期,总数没有。 emi,没有。付费的emi和没有。无偿的emi。这是我的询问。
SELECT MAX(emi_date)AS pay_date,
(SELECT MAX(emi_date) FROM loan_emi WHERE l_id=a.l_id AND is_paid=0
)AS last_date,
(SELECT COUNT(id) FROM loan_emi WHERE l_id=a.l_id
)AS tenor,
(SELECT COUNT(id) FROM loan_emi WHERE l_id=a.l_id AND is_paid=1
)AS paid,
(SELECT COUNT(id) FROM loan_emi WHERE l_id=a.l_id AND is_paid=0
)AS unpaid
FROM loan_emi a
WHERE id =" + lId + "
AND is_paid=1 GROUP BY l_id
但这是多个子查询。请帮我简化一下。提前谢谢。
答案 0 :(得分:3)
只需为每个字段添加一个case / when的单个查询。这样,对于所讨论的ID的所有记录,没有连接,没有子查询,它是一次传递。另外,正如我所说的那样,您可能希望PARAMETERIZE您的查询指明相关帐户的ID ...
SELECT
MAX( case when is_paid = 1 then emi_date else null end ) as Pay_Date,
MAX( case when is_paid = 0 then emi_date else null end ) as Last_Date,
COUNT(*) as Tenor,
SUM( case when is_paid = 1 then 1 else 0 end ) as Paid,
SUM( case when is_paid = 0 then 1 else 0 end ) as Unpaid
from
loan_emi
where
id = ?ParameterizeYourIncomingID
group by
l_id