目前尚不清楚您希望如何返回总和,或者您是否仍希望将部分总和与总数一起返回。
如果您只需要总值,请使用以下查询而不是其他两个:
SELECT
Total = SUM(Weight)
FROM dbo.tbl_insertxmldetails
WHERE x.OrderName LIKE @jobno + '%'
AND Section IN (
SELECT Material
FROM [Mst_tbl_ExtMaterialGroupList]
WHERE [Ext# Matl Group] IN ('PP04', 'PP12')
)
;
如果您想要所有三个值,您应该指定是否要将它们作为单行的单独列:
PP04 PP12 Total
----- ----- -----
… … …
或在单个列中但在单独的行中:
Ext# Matl Group Weight
--------------- ------
PP04 …
PP12 …
Total …
如果是前者(单行,单独的列),这是实现这一目标的一种方法:
SELECT
PP04 = SUM(CASE m.[Ext# Matl Group] WHEN 'PP04' THEN x.Weight END),
PP12 = SUM(CASE m.[Ext# Matl Group] WHEN 'PP12' THEN x.Weight END),
Total = SUM(x.Weight)
FROM dbo.tbl_insertxmldetails AS x
INNER JOIN Mst_tbl_ExtMaterialGroupList AS m ON x.Section = m.Material
WHERE m.[Ext# Matl Group] IN ('PP04', 'PP12')
AND x.OrderName LIKE @jobno + '%'
;
如果您希望将结果放在单独的行中,那么您可以尝试使用汇总进行分组:
SELECT
[Ext# Matl Group] = COALESCE(m.[Ext# Matl Group], 'Total'),
Weight = SUM(x.Weight)
FROM dbo.tbl_insertxmldetails AS x
INNER JOIN Mst_tbl_ExtMaterialGroupList AS m ON x.Section = m.Material
WHERE m.[Ext# Matl Group] IN ('PP04', 'PP12')
AND x.OrderName LIKE @jobno + '%'
GROUP BY
ROLLUP(m.[Ext# Matl Group])
;
注意:如果您的数据库处于 SQL Server 2000 兼容模式,GROUP BY ROLLUP()
将无法工作。在这种情况下,请使用旧语法:
…
GROUP BY
m.[Ext# Matl Group]
WITH ROLLUP