2013-12-22 80 views
1

我在下面的表格數據:拆分數據在多個列轉換爲行(在SQL或SAS)

Country City1 City2 City3  AverageTemperature 
UK   London Glasgow Manchester 15 
Italy  Rome  Naples Venice  25 
Germany Munich Berlin    20 
USA  New York      25 

與SQL或SAS數據步,我想獲得這種形式的數據:

Country City  AverageTemperature 
UK   London  15 
UK   Glasgow  15 
UK   Manchester 15 
Italy  Rome  25 
Italy  Naples  25 
Italy  Venice  25 
Germany Munich  20 
Germany Berlin  20 
USA  New York 25 

這樣我就可以獲得各行的數據。我曾經想過通過循環三個城市的列,而這個城市並不是空白的,但我不知道如何自信地做到這一點 - 是否可以輕鬆地使用SQL或SAS?只是一個指針,將不勝感激。

回答

2
SELECT COUNTRY, City1, AverageTemperature FROM Table_Name 
UNION ALL 
SELECT COUNTRY, City2, AverageTemperature FROM Table_Name 
UNION ALL 
SELECT COUNTRY, City3, AverageTemperature FROM Table_Name 

爲了讓行,其中市列不爲空,你可以做這樣的事情

SELECT COUNTRY, City1, AverageTemperature FROM Table_Name 
WHERE City1 IS NOT NULL 
UNION ALL 
SELECT COUNTRY, City2, AverageTemperature FROM Table_Name 
WHERE City2 IS NOT NULL 
UNION ALL 
SELECT COUNTRY, City3, AverageTemperature FROM Table_Name 
WHERE City3 IS NOT NULL 
1

可以逆轉置此使用「相對」的標準SQL。這裏,只需要一次掃描數據的方法:

select country, city, averagetemperatur 
from (select t.country, 
      (case when n = 1 then t.city1 
        when n = 2 then t.city2 
        when n = 3 then t.city3 
      end) as city, 
      t.averagetemperature 
    from t cross join 
      (select 1 as n union all select 2 union all select 3) n 
    ) t 
where city is not null; 

爲具有三行(n)創建表的精確語法可以根據數據庫而有所不同。

2

在SAS數據步驟

data out; 
set in; 
array cities[3] city1-city3; 
format city $12.; 
do i=1 to 3; 
    if compress(cities[i]) ^= "" then do; 
    city = cities[i]; 
    output; 
    end; 
end; 
keep country city AverageTemperature; 
run; 
0

宏循環應該做的工作很簡單:

%MACRO Cities ; 
    %DO N=1 %TO 3 ; 
    proc sql ; 
     create table Cities_&N as 
     select Country, City&N as City, AverageTemperature 
     from your_table_name_here 
     where City&N is not null ; 
    quit ; 
    %END ; 

    data Cities ; 
    set Cities_: ; 
    run ; 
%MEND ; 

%Cities ;