我正在尝试将select查询的结果移动到recamt
行,其中lastrecdate
是最大日期,但是我在下面的表格中使用更新查询时给我一个错误。我试图将cardno记录与此子查询链接起来。
子查询:
SELECT cardno
FROM Tbl_Emi e2
WHERE LastRecDate = CAST(GETDATE() AS DATE) AND e2.CardNo = e.CardNo
UPDATE Tbl_Emi
SET RecAmt =
(
SELECT
(
SELECT extraamt
FROM Tbl_Emi e1
WHERE LastRecDate = (SELECT MIN(lastrecdate) FROM Tbl_Emi)
AND e1.CardNo=e.CardNo
)
+
(
SELECT pendamt+trnammt
FROM Tbl_Emi e2
WHERE LastRecDate = CAST(GETDATE() AS DATE) AND e2.CardNo = e.CardNo
)
FROM Tbl_Emi e WHERE e.lastrecdate = CAST(GETDATE() AS DATE)
)
WHERE tbl_emi.lastrecdate = CAST(GETDATE() AS DATE)
Cardno | EMI | Recamt | Trndt | Sts | PendAmt | Trnamt | Extra
5140560000001183 | 1016.00 | 0.00 | 2014-05-23 | R | 0.00 | 1017 | 13
5140560000001191 | 880.00 | 0.00 | 2014-05-23 | R | 0.00 | 880 | 0
5140560000001142 | 934.00 | 0.00 | 2014-05-23 | P | 0.00 | 500 | 0
5140560000001209 | 963.00 | 0.00 | 2014-05-23 | P | 0.00 | 600 | 0
5140560000001175 | 1024.00 | 0.00 | 2014-05-23 | N | 0.00 | 0 | 0
5140560000001167 | 1117.00 | 0.00 | 2014-05-23 | N | 0.00 | 0 | 0
5140560000001159 | 834.00 | 0.00 | 2014-05-23 | N | 0.00 | 0 | 0
5140560000001183 | 1016.00 | 0.00 | 2014-05-25 | N | 30.00 | 1017 | 0
5140560000001191 | 880.00 | 0.00 | 2014-05-25 | N | 0.00 | 880 | 0
5140560000001142 | 934.00 | 0.00 | 2014-05-25 | N | 0.00 | 500 | 0
5140560000001209 | 963.00 | 0.00 | 2014-05-25 | N | 0.00 | 600 | 0
5140560000001175 | 1024.00 | 0.00 | 2014-05-25 | N | 0.00 | 0 | 0
5140560000001167 | 1117.00 | 0.00 | 2014-05-25 | N | 0.00 | 0 | 0
5140560000001159 | 834.00 | 0.00 | 2014-05-25 | N | 0.00 | 0 | 0
答案 0 :(得分:0)
首先,您应该告诉您获得的错误以及您正在使用的SQL Server。从你的代码我猜你使用MSSQL。
但是,您的查询引用了“lastrecdate”列,该列不在您的表中,因此无论如何代码都无法处理该示例数据。
更新:在我提出的解决方案之后的评论之后。不幸的是,我仍然不太清楚预期的解决方案,而且列名不匹配的事实也令人困惑。
UPDATE upd SET Recamt=calc.recamt_total --update each row ith calculated values
FROM Tbl_Emi upd -- Join the calculated update value per CardNo to each row
JOIN (
SELECT te.CardNo,textra.extraamt+te.pentamt+te.trnamt recamt_total --join values from today
FROM Tbl_Emi te
JOIN (SELECT t1.CardNo, t1.extraamt --extraamt value at min_dat
FROM Tbl_Emi t1
JOIN (SELECT t2.CardNo,MIN(t2.Trndt) as min_dat --min_dat for each CardNo
FROM Tbl_Emi t2
GROUP BY t2.CardNo) mindat ON mindat.CardNo=t1.CardNo AND mindat.min_dat=t1.Trndat
) textra ON textra.CardNo=te.CardNo
WHERE te.Trndat=(CAST(GETDATE() AS DATE))
) calc ON upd.CardNo=calc.CardNo