是否可以在条件CASE中创建SELECT语句,如此
SELECT la.*,
(
CASE
WHEN la.SoftDelete = 1
SELECT SUM(la.LoansAmount) FROM loans_account
ELSE
SELECT 0
END
) AS outstanding
FROM loans_account
我试过这个,但它不起作用,我想知道如何去做这样的事情。
答案 0 :(得分:3)
我猜你需要贷款金额的总和,其中softdelete是1
SELECT la.*,
SUM(
CASE
WHEN la.SoftDelete = 1
THEN la.LoansAmount
ELSE
0
END
) AS outstanding
FROM loans_account la
WHERE ...
或者如果你需要整个softdelete为1的总和,那么你可以这样做
SELECT la.*,
SUM(la.LoansAmount) outstanding
FROM loans_account la
WHERE la.SoftDelete = 1
注意总和是聚合函数,没有组,它将作为单个行,假设整个表为一个组
答案 1 :(得分:2)
试试这个
SELECT la.*, CASE
WHEN la.SoftDelete = 1 THEN SUM(la.LoansAmount)
ELSE 0 END AS outstanding
FROM loans_account