我有一张名为 patientinfo 的表格,如下所示:
现在,我想要的是从表A 获取PatientId和PatientName今天加入表B 的付款日期和SUM(paymentTotal),SUM(paymentPaid)但最后一行付款保留。
简单来说,我希望所有今天的患者都支付总金额和支付金额,但是最后一行支付费用。
从图形上看,我想要的应该是:
patientId paymentTotal paymentPaid paymentRemaining
252 123500 118500 5000
253 60000 55000 5000
254 17500 17500 0
258 5800 0 5800
注意:记录应为当前日期。
任何帮助?
到目前为止我做了什么:
SELECT a.patientId , a.patientName, b.paymentTotal , b.paymentPaid , b.paymentRemaining FROM
patientinfo a
inner join
(
SELECT patienId , SUM(paymentTotal) as paymentTotal ,SUM(paymentPaid) as paymentPaid,
MAX(paymentRemaining) as paymentRemaining
FROM tblpayment WHERE paymentDate LIKE '%$date%' GROUP BY patienId
)b
on a.patientId = b.patienId
一切都很好,但是这个查询中的错误是它给了我第一个值paymentRemaining的值。然而,我想要付款的最后一个值,它给我MAX值。我该怎么用Max替换这个?
修改
我的问题有点不对劲。我不希望MAX支付剩余,但最后一行支付剩余的患者ID。
答案 0 :(得分:1)
MIN
只需要MAX
而不是LEFT JOIN
:
SELECT DISTINCT
t.patientId,
b.paymentTotal ,
b.paymentPaid , b.paymentRemaining
FROM tblpayment AS t
LEFT JOIN patientinfo a ON t.patientId = a.patientId
LEFT join
(
SELECT patientId , SUM(paymentTotal) as paymentTotal,
SUM(paymentPaid) as paymentPaid,
MIN(paymentRemaining) as paymentRemaining
FROM tblpayment
GROUP BY patientId
) b on t.patientId = b.patientId
这将为您提供您想要的内容:
| patientId | paymentTotal | paymentPaid | paymentRemaining |
|-----------|--------------|-------------|------------------|
| 252 | 123500 | 118500 | 5000 |
| 253 | 60000 | 55000 | 5000 |
| 254 | 17500 | 17500 | 0 |
| 258 | 5800 | 0 | 5800 |
<强>更新强>
如果你想要最后一行,那么它将是每个patientid的最新日期。然后试试这个:
SELECT DISTINCT
t.patientId,
b.paymentTotal ,
b.paymentPaid ,
t.paymentRemaining
FROM
(
a.patientId, paymentRemaining, paymentDate
FROM tblpayment AS t
LEFT JOIN patientinfo a ON t.patientId = a.patientId
) AS t
INNER join
(
SELECT patientId , SUM(paymentTotal) as paymentTotal,
SUM(paymentPaid) as paymentPaid
FROM tblpayment
GROUP BY patientId
) b on t.patientId = b.patientId
INNER JOIN
(
SELECT patientId, MAX(paymentDate) AS LatestDate
FROM tblpayment
GROUP BY patientId
) AS s ON s.patientId = t.patientId AND t.paymentDate = s.LatestDate