我如何将这些查询最恰当地写入单个语句中

时间:2017-11-07 06:48:36

标签: sql-server

我正在尝试将查询下面的内容写入单个语句中。

  • "的 CoverPageID "是CoverPageOthersCosts的主键列 表
  • "的 CoverPageID "是CoverPages的主键列。
  • "的 OurFileNo " column是CoverPages表中的外键列。
SELECT SUM(o.OutPrice) AS ShareOnSaving
FROM CoverPageOthersCosts AS o WITH
    INNER JOIN CoverPages AS c WITH ON o.CoverPageID = c.CoverPageID
WHERE c.OurFileNo = @OurFileNo AND o.DescID IN (1, 2, 3)

SELECT SUM(o.OutPrice) AS CommunicationCost
FROM CoverPageOthersCosts AS o WITH
    INNER JOIN CoverPages AS c WITH ON o.CoverPageID = c.CoverPageID
WHERE c.OurFileNo = @OurFileNo AND o.DescID = 6

SELECT SUM(o.OutPrice) AS HandlingFee
FROM CoverPageOthersCosts AS o WITH
    INNER JOIN CoverPages AS c WITH ON o.CoverPageID = c.CoverPageID
WHERE c.OurFileNo = @OurFileNo AND o.DescID IN (7, 8, 9)

2 个答案:

答案 0 :(得分:1)

使用条件聚合:

SELECT
    SUM(CASE WHEN o.DescID IN (1,2,3) THEN o.OutPrice END) AS ShareOnSaving,
    SUM(CASE WHEN o.DescID = 6        THEN o.OutPrice END) AS CommunicationCost,
    SUM(CASE WHEN o.DescID IN (7,8,9) THEN o.OutPrice END) AS HandlingFee
FROM CoverPageOthersCosts o
INNER JOIN CoverPages c
    ON o.CoverPageID = c.CoverPageID
WHERE
    c.OurFileNol = @OurFileNo;

我们可以使用CASE表达式在表格的一次传递中同时计算三个总和中的每一个。请注意,通过单独执行每个总和,您实际上可能会获得更好的性能。

答案 1 :(得分:0)

实现这一目标的简单方法是添加像这样的案例

SELECT 
  SUM(
      CASE WHEN o.DescID IN (1, 2, 3) THEN o.OutPrice ELSE 0 END
      ) AS ShareOnSaving,
  SUM(CASE WHEN o.DescID 6 THEN o.OutPrice ELSE 0 END) AS CommunicationCost,
  SUM(CASE WHEN o.DescID IN (7, 8, 9) THEN o.OutPrice ELSE 0 END) AS HandlingFee
FROM CoverPageOthersCosts AS o WITH
    INNER JOIN CoverPages AS c WITH ON o.CoverPageID = c.CoverPageID
WHERE c.OurFileNo = @OurFileNo