如何获得计算值的求和

时间:2012-06-18 07:06:22

标签: sql-server sql-server-2008 sql-server-2005

        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。如何在单个语句中编写查询。

2 个答案:

答案 0 :(得分:0)

create procedure calcProc as
   declare @returnValue int

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

   select @returnValue 
go

答案 1 :(得分: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