0
        select sum(Weight) as 'PP04' from dbo.tbl_insertxmldetails where 
        Section in (select Material from [Mst_tbl_ExtMaterialGroupList] 
        where [Ext# Matl Group] = 'PP04') and
        OrderName like @jobno+'%'

--PP12

         select sum(Weight) as 'PP12' from dbo.tbl_insertxmldetails where 
         Section in (select Material from [Mst_tbl_ExtMaterialGroupList] 
         where [Ext# Matl Group] = 'PP12') and
         OrderName like @jobno+'%'

我想编写存储过程来计算同一存储过程中的一些 PP04 和 PP12。如何在单个语句中编写查询。

4

2 回答 2

0

目前尚不清楚您希望如何返回总和,或者您是否仍希望将部分总和与总数一起返回。

如果您只需要总值,请使用以下查询而不是其他两个:

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
于 2012-06-19T07:18:21.710 回答
0
create procedure calcProc as
   declare @returnValue int

   select @returnValue = sum(Weight) as 'PP04' ...
   select @returnValue = @returnValue  + sum(Weight) as 'PP12' ...

   select @returnValue 
go
于 2012-06-18T07:08:33.670 回答