sql - 行之间的复杂计算过程其中之一可能为空

标签 sql sql-server

我这一行有一个复杂的计算过程 如果我的条件等于 true 那么我想对两个字段(val1)进行乘法 对另外两个字段进行另一个乘法(val 2) 然后我计算总值的百分比 ((val1 + val2) * 10%)/100 问题是任何条件可能等于 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

最佳答案

这是你想要的吗?

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;

关于sql - 行之间的复杂计算过程其中之一可能为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41529012/

相关文章:

sql - 简单表设计的最佳 sql 查询

mysql - 如何从 MYSQL 中的行创建水平列?

sql - 用于将查询中的表保存为 csv 的 Flask 按钮

sql-server - 用于插入 SQL Server 的 VBA 空字符串

sql-server - 存储过程中 varchar 输出参数的用途是什么 - 不能 'return @myvarchar' 但可以 'select @myvarchar'

sql - 根据最终值查找最大值

mySQL 5 个表的多重联接出现超时错误

sql-server - 从组中选择前 1 个并在查询中排序

c++ - 如何使用新的 SQL Server Native Client 将 datetime 迁移到 datetime2

sql - 在 postgres 中选择时间戳记录