これを試してみると、月の番号を取得する部分が難しく、カラム名を使用しています。カラム名が同じでない場合は、その部分を変更する必要があります(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.
ProductIdとItem Idは同じですか? – Lucky
期待される出力についてもっと詳しく説明してください。関連する入力と出力を追加してみてください。提供されたサンプルデータは役に立たない。 – DarkKnight