[英]Dynamic Pivot Table with date column
I have a table in which information about a stock for an items are available. 我有一个表,其中提供有关某项物品的库存信息。
This is how the table looks like: 该表如下所示:
ITEMCODE DATE INSTOCK
-----------------------------
ABC001 2019-01-04 10
ABC001 2019-02-04 10
ABC001 2019-03-04 10
ABC001 2019-04-04 5
ABC001 2019-05-04 5
Is it possible to get output like this: 是否有可能得到这样的输出:
Itemcode 01/04/2019 02/04/2019 03/04/2019 04/04/2019 05/04/2019
-------------------------------------------------------------------------
ABC001 10 10 10 5 5
This is the query which i have used... 这是我使用过的查询...
SELECT T0.ITEMCODE,T0.INSTOCK
FROM DBO.TABLE_2 T0
WHERE T0.DATE >='[%0]'AND T0.DATE <= '[%1]'
But after doing some research, I have found out its possible using pivot table... 但是经过一些研究,我发现了使用数据透视表的可能性。
How to modify my query in order to get the desired output 如何修改我的查询以获得所需的输出
I was able to get it with the code below, you just need to replace #table with your table name. 我可以通过下面的代码来获取它,您只需要用表名替换#table即可。 Also ignore the first part of the code that sets up the table. 也忽略设置表的代码的第一部分。
There are similar questions/answers here: SQL Server dynamic PIVOT query? 这里有类似的问题/答案: SQL Server动态PIVOT查询?
-------------------------------------------------------------------
IF OBJECT_ID('tempdb..#table') IS NOT NULL
BEGIN
DROP TABLE #table
END
CREATE TABLE #table(ITEMCODE VARCHAR(10),DATE date,INSTOCK int)
insert into #table values('ABC001','2019-01-04',10)
insert into #table values('ABC001','2019-02-04',10)
insert into #table values('ABC001','2019-03-04',10)
insert into #table values('ABC001','2019-04-04',5)
insert into #table values('ABC001','2019-05-04',5)
-------------------------------------------------------------------
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.DATE)
FROM #table c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ITEMCODE, ' + @cols + ' from
(
select ITEMCODE
, DATE
, INSTOCK
from #table
) x
pivot
(
sum(INSTOCK)
for DATE in (' + @cols + ')
) p '
execute(@query)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.