0

我有一张这样的桌子:

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

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

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

你能帮我吗?

4

2 回答 2

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
于 2013-05-27T12:27:24.130 回答
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
于 2013-05-27T12:59:34.137 回答