将列转换为SQL Server 2008中的行

时间:2016-07-05 03:27:14

标签: sql-server sql-server-2008 pivot

我有这个数据表。每行代表6个月的数据(数量)。

EX:年= 2016年,期限= 1表示Mon1至Mon6为1月至6月

如果Term = 2表示7月至12月。

enter image description here

以上数据我必须如下所示。需要3列数据,如

enter image description here

所以每个产品必须是当月的12个月数据。

指,当月6月,2016年6月至2017年5月(包括当月)

您能否建议使用某些脚本从上表中检索此数据?

1 个答案:

答案 0 :(得分:0)

试试这个,得到月份数的部分很棘手,我使用了列名,如果列名不相同,你需要更改那部分,即mon1,mon2等等。

DECLARE @MyTable TABLE (ProductID INT, [Year] INT, Team INT, Mon1 INT, Mon2 INT, Mon3 INT, Mon4 INT, Mon5 INT, Mon6 INT)

INSERT INTO @MyTable
VALUES   (1, 2016, 1, 10,20,30,40,50,60) 
        ,(1, 2016, 2, 10,20,30,40,50,60)        
        ,(1, 2017, 1, 10,20,30,40,50,60)
        ,(1, 2017, 2, 10,20,30,40,50,60)
        ,(2, 2016, 1, 10,20,30,40,50,60) 
        ,(2, 2016, 2, 10,20,30,40,50,60)        
        ,(2, 2017, 1, 10,20,30,40,50,60)
        ,(2, 2017, 2, 10,20,30,40,50,60)
        ,(3, 2016, 1, 10,20,30,40,50,60) 
        ,(3, 2016, 2, 10,20,30,40,50,60)        
        ,(3, 2017, 1, 10,20,30,40,50,60)
        ,(3, 2017, 2, 10,20,30,40,50,60)
        ,(4, 2016, 1, 10,20,30,40,50,60) 
        ,(4, 2016, 2, 10,20,30,40,50,60)        
        ,(4, 2017, 1, 10,20,30,40,50,60)
        ,(4, 2017, 2, 10,20,30,40,50,60)

DECLARE @FromYear INT, @FromYearMonth INT, @ToYear INT, @ToYearMonth INT

-- Get from - to yearmonth base on current date.
SELECT  @FromYear = YEAR(GETDATE()), 
        @ToYear = YEAR( DATEADD(month,11,GETDATE()))  -- add 11 months as it starts from current month

SELECT  @FromYearMonth = @FromYear * 100 + MONTH(GETDATE()), 
        @ToYearMonth = @ToYear * 100 + MONTH( DATEADD(month,11,GETDATE())) 

SELECT  @FromYear, @ToYear, @FromYearMonth, @ToYearMonth  -- check the dates.

;WITH CTE AS 
(
    SELECT 
        ProductID, 
        [Year], 
        Team, 
        Quantity, 
        CASE WHEN Team = 2 THEN RIGHT(Months,1) + 6 ELSE RIGHT(Months,1) END Mon, -- get month number
        ([Year] * 100) + CASE WHEN Team = 2 THEN RIGHT(Months,1) + 6 ELSE RIGHT(Months,1) END YearMonth -- get YearMonth value
    FROM (  SELECT *
            FROM @MyTable
            WHERE [YEAR] BETWEEN @FromYear AND @ToYear -- filter data for year range
    ) x
    UNPIVOT
    ( Quantity FOR Months IN (Mon1,Mon2,Mon3,Mon4,Mon5,Mon6)        -- deflat row-cols
    ) p
) 
SELECT ProductID, YearMonth, Quantity, Team, Mon
FROM CTE 
WHERE YearMonth BETWEEN @FromYearMonth AND @ToYearMonth -- filer final data.