2014-01-20 76 views
0

我想創建一個查詢,會給我一個表列數的,我在一列連接表在一個循環中

我最初的表看起來像這樣不同值的數量:

tester_ID|trial|result 

example for data

而且不是每個測試都必須有結果爲每個審判

我想讓這樣的事情:

tester_ID|trial 1|trial 2|trial .... 

example for possible result

的問題是我不知道如何使加盟循環 這將去了所有的測試,並導致在寫每一個測試人員與他的結果行

+1

我真的很難理解這個問題...... Information_Schema.Columns給你一個列表在數據庫(與他們的表),你可以用它來動態建立你的查詢? – Liath

+0

請顯示一些示例數據和預期結果。 – okrumnow

+0

我上傳的例子 –

回答

0

希望這有助於你

create table tableA 
(
    tester_ID int, 
    trial int, 
    result varchar 
); 

insert into tableA values 
(1, 10, 'P'), 
(2, 12, 'q'), 
(3, 13, 'w'), 
(4, 14, 'e'), 
(5, 15, 'h'), 

靜態版本,已經值硬編碼爲支點:

select * 
from 
(
    select tester_ID , 
    'Trail_' + cast(ROW_NUMBER() over(PARTITION by tester_ID order by tester_ID desc) as varchar(10)) col    
    from tableA 
) x 
pivot 
(
    max(value) 
    for col in ([Trail_1], [Trail_2], [Trail_3], [Trail_4], 
       [Trail_5]) 
) p 

否則你必須去動版

DECLARE @cols AS NVARCHAR(MAX), 
@query AS NVARCHAR(MAX) 

select @cols = STUFF((SELECT ',' + QUOTENAME('Trail_' + cast(x.rn as varchar(10))) 
        from tableA 
        cross apply 
        (
         select ROW_NUMBER() over(PARTITION by tester_ID order by tester_ID desc) rn 
         from tableA 
        ) x 
        group by x.rn 
        order by x.rn 
      FOR XML PATH(''), TYPE 
      ).value('.', 'NVARCHAR(MAX)') 
     ,1,1,'') 

set @query = 'SELECT id, ' + @cols + ' from 
      (
       select tester_ID, 
        ''Timeline_'' + cast(ROW_NUMBER() over(PARTITION by tester_ID order by tester_ID desc) as varchar(10)) col 

       from tableA 
      ) x 
      pivot 
      (
       max(value) 
       for col in (' + @cols + ') 
      ) p ' 

execute(@query) 
+0

所以你知道pivoting ... –

+0

@thedarksideofthemoon我希望如此 –

+0

我認爲你的問題是在'cast(ROW_NUMBER()(PARTITION由tester_ID order by tester_ID desc)':當我執行它時,我只是'Trial_1 '對於所有行 –

0

如果我理解正確的,你想是這樣的:

SELECT r.tester_ID,CONCAT(r.Trail_1,r.Trail_2,r.Trail_3,r.Trail_4,r.Trail_5) AS trails 
FROM (
    SELECT * 
    FROM (
      SELECT tester_ID , 
      'Trail_' + CAST(DENSE_RANK() OVER(ORDER BY trial DESC) AS VARCHAR(10)) col    
      FROM tableA 
      ) AS x 
      PIVOT 
      (
       MAX(col) 
       FOR col IN ([Trail_1],[Trail_2],[Trail_3],[Trail_4],[Trail_5]) 
      ) AS p 
     ) AS r 

這是確定的,如果不能有一個有兩條路線或試驗的tester_ID

P.S.也許它可以被優化;)

+0

謝謝,但問題是我不知道有多少試驗有 –