我有一个基本的查询来从表中提取服务总和:
Select Service, Sum(Qty_Sold) as Total
From Services
Where Service in ('1','2','3','4')
Group By Service
输出:
Service Total
1 8
2 9
3 22
4 11
我最近添加了一项新服务,但我想添加一项新服务,该服务将为“7”,并将其添加到“4”服务中。所以 - 我的数据将是:
Service Total
1 8
2 9
3 22
4 11
7 1
但我希望我的输出为:
Service Total
1 8
2 9
3 22
4 12
我试过了:
Select * from
(
Select Case When Service = '7' then '4' Else Service, Sum(Qty_Sold) as Total
From Services
Where Service in ('1','2','3','4','7')
Group By Service)
Group By Services, Total
这仍然不能得到我需要的总数,它只是List的'4'两次。如何将它组合到4和7中以显示我想要的内容?
答案 0 :(得分:1)
试试这个
SELECT
CombinedService, SUM(Total) AS CombinedTotal
FROM
( SELECT
CASE
WHEN Service = '7' THEN '4'
ELSE Service
END AS CombinedService,
SUM(Qty_Sold) AS Total
FROM
Services
WHERE
Service IN ('1', '2', '3', '4', '7')
GROUP BY
Service
) cs
GROUP BY
CombinedService
答案 1 :(得分:0)
您可以创建一个包含ServiceDescriptors'的新表格,而不是弄乱复杂的WHERE子句:
ServiceID ServiceDesc
1 1
2 2
3 3
4 4
7 4
然后,只需基于ServiceDesc求和。当您添加新的ServiceID时,您将更加欣赏此解决方案。
HTH,Jim
答案 2 :(得分:0)
您可以尝试使用CTE加入服务表。
WITH cte(origService, newService) AS (
SELECT * FROM (VALUES (1, 1), (2, 2), (3, 3), (4, 4), (7, 4)) t(o, n)
)
SELECT newService AS Service, sum(Qty_Sold) AS Total
FROM cte
JOIN Services s ON s.Service = cte.origService
GROUP BY newService