2017-06-18 28 views
0

我想知道是否有一個優雅的重構底部3'創建表'段下面,它檢索相同的結果。 我希望推廣一個更大的數據集。 非常感謝提前。SQL:將行數據精確翻轉到列

// These top two lines for viewing in SQLite: 
    .mode column 
    .headers on 

    Create table Data_Table (
    Other varchar(255), 
    Id varchar(255), 
    Value int); 

    INSERT INTO Data_Table (other, id, value) 
    VALUES ('x','a', 1); 

    INSERT INTO Data_Table (other,id, value) 
    VALUES ('y','a', 2); 

    INSERT INTO Data_Table (other,id, value) 
    VALUES ('x','b', 2); 

    INSERT INTO Data_Table (other,id, value) 
    VALUES ('y','b', 3); 

    Create table SubTable_A as 
    select t1.other as other, t1.value as a 
    from Data_table as t1 
    where t1.id = 'a'; 

    Create table SubTable_B as 
    select t2.value as b 
    from Data_table as t2 
    where t2.id = 'b'; 

    Create table Soln_Table as 
    select t1.*, t2.* 
    from SubTable_A as t1, SubTable_B as t2 
    where t1.rowid = t2.rowid; 

底線,我們現在有這樣的數據集

other  a   b   

    ---------- ---------- ---------- 

    x   1   2   

    y   2   3 
+0

您在使用MySQL或SQLite的?請正確標記。 –

+0

謝謝GL - >更新標籤/ SQLite – beast

回答

0

可以使用條件彙總:

select t.other, 
     max(case when t.id = 'a' then value end) as a, 
     max(case when t.id = 'b' then value end) as b 
from Data_Table t 
group by t.other; 
+0

謝謝Gordon! – beast