试试这个——
询问:
DECLARE @temp TABLE
(
EntryID INT
, Name NVARCHAR(50)
, Qty INT
)
INSERT INTO @temp (EntryID, Name, qty)
VALUES
(12, 'Global' , 5),
(12, 'In Europe' , 15),
(12, 'In Asia' , 21),
(12, 'In US' , 53),
(18, 'Max' , 5),
(18, 'In Europe' , 35),
(18, 'In Asia' , 63),
(18, 'In US' , 85)
SELECT
EntryID
, [In Europe] = SUM(CASE WHEN Name = 'In Europe' THEN Qty ELSE 0 END)
, [In Asia] = SUM(CASE WHEN Name = 'In Asia' THEN Qty ELSE 0 END)
, [In US] = SUM(CASE WHEN Name = 'In US' THEN Qty ELSE 0 END)
, [Global] = SUM(CASE WHEN Name = 'Global' THEN Qty ELSE 0 END)
FROM @temp
GROUP BY EntryID
输出:
EntryID In Europe In Asia In US Global
----------- ----------- ----------- ----------- -----------
12 15 21 53 5
18 35 63 85 0
SP:
CREATE PROCEDURE dbo.usp_GetEntryID
@EntryID INT
AS BEGIN
SET NOCOUNT ON;
SELECT
EntryID
, [In Europe] = SUM(CASE WHEN Name = 'In Europe' THEN Qty ELSE 0 END)
, [In Asia] = SUM(CASE WHEN Name = 'In Asia' THEN Qty ELSE 0 END)
, [In US] = SUM(CASE WHEN Name = 'In US' THEN Qty ELSE 0 END)
, [Global] = SUM(CASE WHEN Name = 'Global' THEN Qty ELSE 0 END)
FROM dbo.table1 --<-- your table
WHERE EntryID = @EntryID
GROUP BY EntryID
RETURN 0
END