使用SQL到CASE语句中的计算重写子查询

时间:2017-03-27 07:31:17

标签: sql sql-server

作为更大查询的一部分,我有一些子查询,我想转换为CASE语句。

子查询看起来像这样(并且有效):

(SELECT (((SUM(DAm)-(SUM(StcCst)*-1))*100)/NULLIF(SUM(DAm),0)) AS 'DG' FROM [F0001].[dbo].[ProdTr] WHERE AcYrPr = '201601' AND ProdTr.TrTp = 1 AND [F0001].[dbo].[ProdTr].CustNo = '12773') AS dg_period_1

但是,我似乎没有找到任何合理的方法将其放入CASE语句中。

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:3)

(
    SELECT  CASE
                WHEN SUM(t1.DAm) <> 0
                THEN (SUM(t1.DAm) + SUM(t1.StcCst)) * 100 / SUM(t1.DAm)
                ELSE 0 /* or whatever you want to have in this case */
            END AS 'DG' 
    FROM    [F0001].[dbo].[ProdTr] t1
    WHERE   t1.AcYrPr = '201601' AND
            t1.TrTp = 1 AND
            t1.CustNo = '12773'
) AS dg_period_1

我还删除了一些不需要的括号并简化了操作(x - (y * -1) = x + y)

答案 1 :(得分:1)

如果要在SUM(DAm)为null或0时返回null,则可以对CASE使用以下语句。

(SELECT CASE
              WHEN SUM(DAm) IS NOT NULL and SUM(DAm)  <> 0 THEN (((SUM(DAm) - (SUM(StcCst) * -1)) * 100) /SUM(DAm))
              ELSE NULL
          END AS 'DG'
   FROM [F0001].[dbo].[ProdTr]
   WHERE AcYrPr = '201601'
     AND ProdTr.TrTp = 1
     AND [F0001].[dbo].[ProdTr].CustNo = '12773') AS dg_period_1