2014-02-17 62 views
1

我有以下表梳理多行到一行

Index BookNumber 
    2   51 
    2   52 
    2   53 
    1   41 
    1   42 
    1   43 

我試圖想出以下輸出

Index BookNumber1 Booknumber2 Booknumber3 
---------------------------------------------- 
    1   41    42   43 
    2   51    52   53 

我能想出下面的查詢,但是輸出是意外

SELECT DISTINCT 
    index, 
    CASE WHEN index = 1 THEN Booknumber END AS BookNumber1, 
    CASE WHEN index = 2 THEN Booknumber END AS BookNumber2, 
    CASE WHEN index = 3 THEN Booknumber END AS BookNumber3 
FROM Mytable; 

我獲得以下輸出

Index BN1 BN2 BN3 
------------------------------ 
    1  41  null null 
    1  null 42  null 
    1  null null 43 
    2  51  null null 
    2  null 52  null 
    2  null null 53 

有沒有辦法將它壓縮成只有2行?

+1

歡迎StackOverflow上:如果您發佈的代碼,XML或數據樣本,** **請在突出的那些行文本編輯器並點擊編輯器工具欄上的「代碼示例」按鈕(「{}」),以精確地格式化和語法突出顯示它!那麼你不需要任何這些蹩腳的' '和'
'標籤! –

回答

0

我不太清楚如何在您的查詢的index匹配數據中的index列。但您要查詢的是:

SELECT index, 
     max(CASE WHEN index = 1 THEN Booknumber END) AS BookNumber1 , 
     max(CASE WHEN index = 2 THEN Booknumber END) AS BookNumber2, 
     max(CASE WHEN index = 3 THEN Booknumber END) AS BookNumber3 
FROM Mytable 
GROUP BY index; 

給你的數據,查詢似乎更像是:

SELECT index, 
     max(CASE WHEN ind = 1 THEN Booknumber END) AS BookNumber1 , 
     max(CASE WHEN ind = 2 THEN Booknumber END) AS BookNumber2, 
     max(CASE WHEN ind = 3 THEN Booknumber END) AS BookNumber3 
FROM (select mt.*, row_number() over (partition by index order by BookNumber) as ind 
     from Mytable mt 
    ) mt 
GROUP BY index; 

順便說一句,「指數」是一個保留字,所以我認爲這是隻是另一個列名的佔位符。否則,您需要用雙引號或方括號將其轉義。

0

假設總有3個或更少的每個索引書號,你可以使用:

with data as 
(select idx, 
     booknumber as bn1, 
     lag(booknumber, 1) over(partition by idx order by idx, booknumber) as bn2, 
     lag(booknumber, 2) over(partition by idx order by idx, booknumber) as bn3 
    from books) 
select * 
    from data 
where data.bn1 = (select max(x.bn1) from data x where x.idx = data.idx) 

sqlfiddle演示是在這裏:http://sqlfiddle.com/#!6/8dc82/5/0

0

不要忘記,索引是一個保留字。我個人更喜歡不使用保留字作爲列名,但可以使用方括號進行補償,如我的示例中所示。

這將從SQLSERVER工作2008+

declare @t table([Index] int, BookNumber int) 
insert @t values 
(2,51),(2,52),(2,53),(1,41),(1,42),(1,43) 

;with cte as 
(
select [Index], BookNumber, 
row_number() over (partition by [Index] order by BookNumber) rn 
from @t 
) 
select [Index], [1] as Booknumber1, [2] as Booknumber2, [3] as Booknumber3 
from cte 
pivot (max([booknumber]) FOR [rn] IN ([1],[2],[3])) AS pvt 

結果:

Index Booknumber1 Booknumber2 Booknumber3 
1  41   42   43 
2  51   52   53