添加多个结果形成多个子查询

时间:2014-05-24 08:25:33

标签: sql sql-server

我正在运行SQL Server查询以获取交易金额和待处理金额以及额外金额的总和。我发现这样做的最佳解决方案是使用子查询,因此我使用子查询,这是最快的方法。但是,虽然我可以从每个子查询中提取数量,但我无法弄清楚如何将它们一起添加,因此我可以按总数进行排序。

这是当前的查询:

 SELECT 
     *, trans + pend + extra AS totalamount
 FROM 
     (SELECT
          (SELECT trnammt
           FROM Tbl_Emi
           WHERE Status IN ('N', 'P')
             AND lastrecdate = (CAST(GETDATE() AS DATE))
             AND CardNo = CardNo) AS TRANS,
          (SELECT pendamt
           FROM Tbl_Emi
           WHERE Status IN ('N', 'P')
             AND lastrecdate = (CAST(GETDATE() AS DATE))
             AND CardNo = CardNo) AS PEND,
          (SELECT extraamt
           FROM Tbl_Emi
           WHERE Status IN ('N', 'P')
             AND lastrecdate = (SELECT MIN(lastrecdate) FROM Tbl_Emi)
             AND CardNo = CardNo) AS EXTRA
    FROM 
        Tbl_Emi) q

我需要将trans和pend以及extra添加到一起以获得'totalamount'。 SQL Server不允许您使用简单的语法对别名进行计算,但我认为还有另一种方法可以做到这一点吗?

2 个答案:

答案 0 :(得分:0)

如果您只想要trans + pend + extra的总和,则需要更改标准部分

 SELECT CASE WHEN (lastrecdate = (CAST(GETDATE() AS DATE))
                 AND CardNo = CardNo) THEN trnammt
             ELSE 0
        END +
        CASE WHEN (pendamt = (CAST(GETDATE() AS DATE))
                 AND CardNo = CardNo) THEN trnammt
             ELSE 0
        END +
        CASE WHEN (lastrecdate = (SELECT MIN(lastrecdate) FROM Tbl_Emi)
                 AND CardNo = CardNo) THEN trnammt
             ELSE 0
        END AS totalamount
  WHERE Status IN ('N','P') 

答案 1 :(得分:0)

以下是我可以轻易看到的三个问题:

  • 子查询未聚合,因此如果它们返回多行,则会出现错误。
  • 相关条件仅涉及子查询(因此它们并不真正相关)。
  • 结果可能为NULL,因此总和为NULL

此版本修复了以下三个问题:

 SELECT e.*,
        (COALESCE(trans, 0) + COALESCE(pend, 0) + COALESCE(extra, 0)) AS totalamount
   FROM (
         SELECT (
                 SELECT SUM(trnammt)
                   FROM Tbl_Emi e2
                  WHERE Status IN ('N','P')
                    AND lastrecdate = (CAST(GETDATE() AS DATE))
                    AND e2.CardNo = e.CardNo
                ) AS trans,
                (
                 SELECT sum(pendamt)
                   FROM Tbl_Emi e2
                  WHERE Status IN ('N','P')
                    AND lastrecdate = (CAST(GETDATE() AS DATE))
                    AND e2.CardNo = e.CardNo
                ) AS pend,
                (
                 SELECT sum(extraamt)
                   FROM Tbl_Emi e2
                  WHERE Status IN ('N','P')
                    AND lastrecdate = (SELECT MIN(lastrecdate) FROM Tbl_Emi)
                    AND e2.CardNo = e.CardNo
                ) AS extra
           FROM Tbl_Emi e 
        ) e