我正在尝试将查询下面的内容写入单个语句中。
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)
答案 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