我有一张表@tbl_price
,如此:
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)
我需要进行动态旋转以显示如下输出:
date 10001 20003
-------------------------------------------
2018-03-01 24.8 30.89
答案 0 :(得分:1)
如果您可以使用临时表或真实表而不是表变量,则此查询应该可以很好地为您工作。它将动态返回列表中每个股票价格的新列。
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;