简体   繁体   中英

Dynamic pivoting in SQL Server

I have a table @tbl_price like so:

declare @tbl_price table ([date] date, stockid varchar(50), price float)

insert into @tbl_price ([date], stockid, price)
values ('2018-03-01', 10001, 24.8),
       ('2018-03-02', 10001, 26.2),
       ('2018-03-03', 10001, 27.8),
       ('2018-03-04', 10001, 28.8),
       ('2018-03-05', 10001, 21.8),
       ('2018-03-06', 10001, 23.8),
       ('2018-03-01', 20003, 30.89),
       ('2018-03-02', 20003, 33.00),
       ('2018-03-03', 20003, 34.8),
       ('2018-03-04', 20003, 34.2),
       ('2018-03-05', 20003, 33.8),
       ('2018-03-06', 20003, 43.8)

I need to do dynamic pivoting to show output like below:

date                    10001        20003
-------------------------------------------
2018-03-01              24.8         30.89

If you can use a temp table or a real table instead of a table variable, this query should work nicely for you. It will dynamically return a new column for the price of every stock in your list.

CREATE TABLE #tbl_price
(
    [date]          DATE,
    stockid         VARCHAR(50),
    price           FLOAT
);

INSERT INTO #tbl_price
(
    [date],
    stockid,
    price
) VALUES
('2018-03-01',10001,24.8),
('2018-03-02',10001,26.2),
('2018-03-03',10001,27.8),
('2018-03-04',10001,28.8),
('2018-03-05',10001,21.8),
('2018-03-06',10001,23.8),
('2018-03-01',20003,30.89),
('2018-03-02',20003,33.00),
('2018-03-03',20003,34.8),
('2018-03-04',20003,34.2),
('2018-03-05',20003,33.8),
('2018-03-06',20003,43.8);

DECLARE @Stocks     NVARCHAR(MAX);
DECLARE @Query      NVARCHAR(MAX);

SET @Stocks =
    STUFF
    (
        (
            SELECT DISTINCT ',' + QUOTENAME(stockid) 
            FROM #tbl_price
            FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)'),
        1,
        1,
        ''
    );

SET @Query =
    'SELECT date, ' + @Stocks +
    ' FROM 
    (
        SELECT
            date,
            stockid,
            price
        FROM #tbl_price
    ) x
    PIVOT 
    (
      MAX(price)
      FOR stockid IN (' + @Stocks + ')
    ) p';

EXEC sp_executesql @Query;

DROP TABLE #tbl_price;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM