如何合并存储过程中的值?

时间:2013-05-27 11:18:02

标签: sql-server tsql stored-procedures group-by

我有一张这样的表:

Entry ID    |     Name    |     qty
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

我想创建一个存储过程,其中我放置一个参数“Entry ID”,exec给出数字@ent = 12给出:

Entry ID    |  In Europe | In Asia  |  In US | Global
12          |    15      |  21      |    53  |   5

你能帮帮我吗?

2 个答案:

答案 0 :(得分:1)

试试这个 -

<强>查询:

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

答案 1 :(得分:1)

试试这个: 这是动态查询,无需在任何地方提及列名称。

CREATE PROC sp_Sample
@EntryID int
As
BEGIN
SET NOCOUNT ON
DECLARE @cols varchar(100)
DECLARE @Query varchar(1000)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(name) 
                    from sample where [Entry Id]=@EntryID
            FOR XML PATH(''), TYPE
            ).value('.', 'VARCHAR(MAX)') 
        ,1,1,'')
set @query 
      = 'SELECT [Entry ID],' + @cols + ' from 
         (
            SELECT [Entry ID],[Name],[Qty]
            FROM sample WHERE [Entry Id]='+cast(@EntryID as varchar(5))+'
         ) x
         pivot 
         (
            min(qty)
            for name in (' + @cols + ')
         ) p '

EXECUTE(@query)

END


exec sp_Sample 18