SQL Server透视和排序

时间:2017-08-23 09:39:05

标签: sql-server

我有一个车间订单表,其中包含物料代码,说明ReleaseDate和所需数量。 如何以数据透视表格式查询结果将使用年份+月份[ReleaseDate]按从最早日期到最晚日期的排序顺序进行数据透视。使用Year + Month作为列。

这是我的查询,但失败了。

 --Declare necessary variables
DECLARE   @SQLQuery AS NVARCHAR(MAX)
DECLARE   @PivotColumns AS NVARCHAR(MAX)

--Get unique values of pivot column  
SELECT   @PivotColumns = COALESCE(@PivotColumns + ',','') + QUOTENAME([YEARMONTH]) 
FROM (SELECT DISTINCT  CONVERT(char(6), cast([releaseddate] as date), 112 ) as [YEARMONTH] FROM [dbo].[ShopOrder]) as PivotQuery

SELECT   @PivotColumns

--Create the dynamic query with all the values for 
--pivot column at runtime

SET   @SQLQuery = 
    N'SELECT ItemCode, ' +   @PivotColumns + '
    FROM [dbo].[ShopOrder] 
    PIVOT( SUM(RequiredQty) 
          FOR [releaseddate] IN (' + @PivotColumns + ')) AS P'

SELECT   @SQLQuery
--Execute dynamic query
EXEC sp_executesql @SQLQuery

这是原始记录

image

结果查询必须像这样

image

2 个答案:

答案 0 :(得分:1)

您没有正确旋转,并且应该在单个字符串中生成列名称。试试这个:

CREATE TABLE ShopOrder (ItemCode VARCHAR(100),[Description] VARCHAR(100),ReleaseDate DATE, RequiredQty INT)
GO
INSERT INTO ShopOrder
VALUES
('A','SLEEVE NUT','08/01/2017',19200)
,('A','SLEEVE NUT','08/02/2017',18000)
,('A','SLEEVE NUT','09/01/2017',17000)
,('B','STARTER','08/03/2017',10000)
,('B','STARTER','08/04/2017',18000)
,('B','STARTER','09/15/2017',16000)

DECLARE @SQLQuery AS NVARCHAR(MAX)
DECLARE @PivotColumns AS NVARCHAR(MAX)

SET @PivotColumns = STUFF(( SELECT  DISTINCT ',[' + CONVERT(char(6), cast(ReleaseDate as date), 112 ) + ']'
                            FROM    ShopOrder
                            ORDER   BY ',[' + CONVERT(char(6), cast(ReleaseDate as date), 112 ) + ']'
                            FOR XML PATH('')),1,1,'')

SET   @SQLQuery = 
N'
SELECT ItemCode,'+ @PivotColumns + '
FROM (SELECT ItemCOde,CONVERT(char(6), cast(ReleaseDate as date),112) ReleaseDate, RequiredQty  
        FROM ShopOrder) AS T
PIVOT( SUM(RequiredQty)
        FOR ReleaseDate IN ('+@PivotColumns+')) AS P
'

SELECT   @SQLQuery
--Execute dynamic query
EXEC sp_executesql @SQLQuery

答案 1 :(得分:1)

在这里,我尝试使用您提供的数据执行数据透视。

<强>查询

Select 
    [ItemCode],
    [Description],
    [2017/8],
    [2017/9]
from
(
select cast(year(ReleasedDate) as nvarchar)+'/'+cast(month(ReleasedDate) as nvarchar) as ReleasedDate,ItemCode,Description,RequiredQty
from shoporder) as PivotData
Pivot
(
sum(RequiredQty) for ReleasedDate in
([2017/8],[2017/9])) as Pivoting
order by ItemCode

<强>输出:

enter image description here

Fiddle