我在这行上有一个复杂的计算过程 如果我的条件等于真,那么我想做两个字段(val1)的乘法 做另一个两个字段的另一个乘法(val 2) 然后我计算总值的百分比((val1 + val2)* 10%)/ 100 问题是任何condotion可能等于false然后结果等于null 这是我的代码
SELECT DISTINCT
r.paymentDate as "Payment Date" ,
r.recivedID as "Recived ID" ,
f.farmerName as "Farmer Name" ,
ra.tips as "percentage ",
( ( (SELECT SUM(od.price * od.kilo) FROM orderDetailsTBL od WHERE od.recivedID = r. recivedID AND r.status = @STATUS AND od.calcType = 'k') +
(SELECT SUM(od.quant * od.price) FROM orderDetailsTBL od WHERE od.recivedID = r. recivedID AND r.status = @STATUS AND od.calcType = 'n') ) * ra.tips) / 100
as [amount]
FROM recivedTBL r
JOIN farmerTBL f ON f.farmerID = r.farmerID
JOIN recivedAccTBL ra ON ra.recivedID = r.recivedID
JOIN orderDetailsTBL od ON od.recivedID = r.recivedID
WHERE (r.paymentDate BETWEEN @D1 AND @D2) AND r.status = @STATUS
如果任何子查询条件等于false,则此查询不返回值 例如:
(SELECT SUM(od.quant * od.price) FROM orderDetailsTBL od WHERE od.recivedID = r. recivedID AND r.status = @STATUS AND od.calcType = 'n') ) * ra.tips) / 100
如果此子查询等于false,则返回的值将为null
答案 0 :(得分:3)
这是你想要的吗?
SELECT r.paymentDate as "Payment Date", r.recivedID as "Recived ID",
f.farmerName as "Farmer Name", ra.tips as "percentage",
SUM((CASE WHEN od.calcType = 'k' THEN od.price * od.kilo
WHEN od.calcType = 'n' THEN od.quant * od.price
END) * ra.tips) / 100 as [amount]
FROM recivedTBL r JOIN
farmerTBL f
ON f.farmerID = r.farmerID JOIN
recivedAccTBL ra
ON ra.recivedID = r.recivedID JOIN
orderDetailsTBL od
ON od.recivedID = r.recivedID
WHERE r.paymentDate BETWEEN @D1 AND @D2 AND r.status = @STATUS
GROUP BY r.paymentDate, r.recivedID, f.farmerName, ra.tips;
答案 1 :(得分:0)
包裹"金额"在:
COALESCE(<your-calc>, 0) as [amount]
如果计算返回NULL,则返回零