2015-05-06 89 views
-1

我真的很新。目前工作的SQL Server 2012年SQL Server表操作

我有以下結構(記錄完整數據表的子集)的表答:

CREATE TABLE [dbo].[TABLE_A](
    [ASSET ID] [float] NULL, 
    [TASK ID] [float] NULL, 
    [IN_YEAR ] [float] NULL, 
    [IN_WEEK] [float] NULL, 
    [FLAG] [nvarchar](1) NULL 
) ON [PRIMARY] 

INSERT INTO TABLE_A 
    ([ASSET ID], [TASK ID], [IN_YEAR], [IN_WEEK], [FLAG]) 
VALUES 
    (1, 1, 2015, 19, 'N'), 
    (1, 1, 2015, 20, 'Y'), 
    (1, 1, 2015, 21, 'N'), 
    (1, 2, 2015, 19, 'Y'), 
    (1, 2, 2015, 20, 'N'), 
    (1, 2, 2015, 21, 'N'), 
    (2, 1, 2015, 19, 'N'), 
    (2, 1, 2015, 20, 'N'), 
    (2, 1, 2015, 21, 'N') 
; 

在表A中,我們總是有相同的週數/年,資產ID和任務ID的每個唯一組合。

,並想將它翻譯成B表結構:

+----------+---------+--------------+--------------+--------------+ 
| Asset ID | Task ID | 2015–WEEK 19 | 2015–WEEK 20 | 2015–WEEK 21 | 
+----------+---------+--------------+--------------+--------------+ 
|  1 |  1 | N   | Y   | N   | 
|  1 |  2 | Y   | N   | N   | 
|  2 |  1 | N   | N   | N   | 
+----------+---------+--------------+--------------+--------------+ 

有什麼想法?

+0

你可能會發現你的答案[這裏](http://stackoverflow.com/questions/13372276/simple-way-to-transpose-columns-and-rows-in-sql)... –

回答

0

給這段代碼嘗試一下尺寸,看看你如何繼續。它首先採用所有獨特的年份/周,然後創建一個選擇列表。然後使用動態T-SQL它創建一個數據透視表,以顯示您所需的佈局:

SELECT DISTINCT CAST(IN_YEAR AS VARCHAR) + '-WEEK '+CAST(IN_WEEK AS VARCHAR) AS VALS 
INTO #VALS 
FROM TABLE_A 

DECLARE @VALS NVARCHAR(500) 
DECLARE @SQL NVARCHAR(MAX) 

SELECT @VALS = COALESCE(@VALS+', ','') + '[' + VALS + ']' FROM #VALS 

SET @SQL = ' 
;WITH CTE AS (
SELECT [ASSET ID], [TASK ID], CAST(IN_YEAR AS VARCHAR) + ''-WEEK ''+CAST(IN_WEEK AS VARCHAR) AS YEARWEEK, FLAG 
FROM TABLE1) 
SELECT [ASSET ID], [TASK ID], '[email protected]+' 
FROM CTE 
PIVOT(MAX(FLAG) FOR YEARWEEK IN ('[email protected]+')) PIV' 
PRINT @SQL 
EXEC (@SQL) 

工作小提琴here

+0

嗨約翰尼,謝謝這麼多的幫助。它似乎與你得到的一個小數據集一起工作,但完整的數據集有近1百萬條記錄。 ASSET ID,TASK ID,IN_YEAR,IN_WEEK是int類型,FLAG是nvarchar(1)。 –

+0

因此它不適用於您的完整數據集?它會拋出任何錯誤嗎? –

+0

HI約翰尼在做了一些小小的更新之後,就像一個魅力!非常感謝你。我開始探索對我而言新的動態SQL。 –