/ / come ottenere la somma del valore calcolato - sql-server, sql-server-2008, sql-server-2005

come ottenere la somma del valore calcolato - 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+"%"

Voglio scrivere una procedura memorizzata per eseguire il Caluclating di alcuni di PP04 e PP12 nella stessa stored procedure. Come posso scrivere una query in una singola istruzione.

risposte:

0 per risposta № 1
create procedure calcProc as
declare @returnValue int

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

select @returnValue
go

0 per risposta № 2

Non è chiaro come si desidera restituire la somma totale o se si desidera comunque restituire le somme parziali insieme al totale.

Se si desidera solo il valore totale, utilizzare la query seguente anziché gli altri due:

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")
)
;

Se si desidera che tutti e tre i valori, è necessario specificare se li si desidera come colonne separate di una singola riga:

PP04   PP12   Total
-----  -----  -----
…      …      …

o in una singola colonna ma in righe separate:

Ext# Matl Group  Weight
---------------  ------
PP04             …
PP12             …
Total            …

Se il precedente (riga singola, colonne separate), ecco un modo per ottenere ciò:

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 + "%"
;

E se vuoi i risultati in righe separate, puoi provare a raggruppare con rollup:

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])
;

Nota: se il database è in modalità compatibile con SQL Server 2000, GROUP BY ROLLUP() non funziona. In questo caso usa la sintassi più vecchia:

…
GROUP BY
m.[Ext# Matl Group]
WITH ROLLUP