2013-05-15 71 views
-5

分組列我想創建查詢表1總結如下:總和其行值

Table1: 
+-----+------+-----+------+ 
|Col1 | Col2 |Col3 | Col4 | 
|1 | 2 |3 | 1 | 
|3 | 2 |1 | 1 | 
|2 | 1 |3 | 1 | 
+-----+------+-----+------+ 
Output: 
+----+---+-----+-----+----+----+      
| | 1 | 2 | 3 | 4 | 5 |  
+----+---+-----+-----+----+----+ 
|Col1| 1 | 2 | 3 | | |  
|Col2| 1 | 4 |  | | |  
|Col3| 1 |  | 6 | | |  
|Col4| 3 |  |  | | | 
+----+---+-----+-----+----+----+          

我的最好的方法是使用變換PIVOT。

+6

請張貼在SQL你最好的嘗試。 – Randy

+0

@Randy,謝謝你的回覆。我發佈了我的最佳嘗試。我的計劃是使TRANSFORM PIVOT脫離這個查詢,因爲我無法在一個查詢中完成。 – matley

+0

編輯您的問題,包括盡力而爲 – Bohemian

回答

3

您將要使用UNION ALL第一,然後應用PIVOT /轉換到unpivot的數據:

transform sum(val) 
select col 
from 
(
    SELECT 'Col1' as col, Col1 as Val 
    FROM test 
    union all 
    SELECT 'Col2' as col, Col2 as Val 
    FROM test 
    union all 
    SELECT 'Col3' as col, Col3 as Val 
    FROM test 
    union all 
    SELECT 'Col4' as col, Col4 as Val 
    FROM test 
) src 
group by col 
pivot val; 

的UNION ALL查詢的多列col1col2等爲多行轉換單一列,那麼你可以應用TRANSFORM功能。

注:此查詢在MS Access 2010中進行測試,並將其返回的結果:

+------+---+---+---+ 
| col | 1 | 2 | 3 | 
+------+---+---+---+ 
| Col1 | 1 | 2 | 3 | 
| Col2 | 1 | 4 | | 
| Col3 | 1 | | 6 | 
| Col4 | 3 | | | 
+------+---+---+---+ 

編輯,根據您的評論,你需要所有的值出現1-5,那麼我會建議使用這些微小的變化。

首先,創建一個包含所有數字的要出現一個表:

create table numbers 
(
    n number 
); 

insert into numbers values (1); 
insert into numbers values (2); 
insert into numbers values (3); 
insert into numbers values (4); 
insert into numbers values (5); 

一旦你擁有所有你想要顯示的數值表,然後創建一個單獨的查詢UNION ALL從上面查詢。下面我查詢創建一個名爲unpiv保存它,但你可以把它叫做什麼:

SELECT 'Col1' as col, Col1 as Val 
FROM test 
union all 
SELECT 'Col2' as col, Col2 as Val 
FROM test 
union all 
SELECT 'Col3' as col, Col3 as Val 
FROM test 
UNION ALL SELECT 'Col4' as col, Col4 as Val 
FROM test; 

以獲得結果的關鍵是創建所有的數字與列的每一個,所以你的列表將使用如下所示:

SELECT col, val 
from numbers, (select distinct col from unpiv); 

這會生成每個列名的笛卡爾式結果,並顯示您想要顯示的數字。最後你將上面的查詢加入到你的查詢中,這樣你就可以對數據進行轉換。最終的查詢是:

transform sum(u.val) 
select src.col 
from 
(
    SELECT col, val 
    from numbers, (select distinct col from unpiv) 
) src 
left join unpiv u 
    on src.col = u.col 
    and src.val = u.val 
group by src.col 
pivot src.val; 

在MS Access 2010測試給出結果:

+------+---+---+---+---+---+ 
| col | 1 | 2 | 3 | 4 | 5 | 
+------+---+---+---+---+---+ 
| Col1 | 1 | 2 | 3 | | | 
| Col2 | 1 | 4 | | | | 
| Col3 | 1 | | 6 | | | 
| Col4 | 3 | | | | | 
+------+---+---+---+---+---+ 
+0

謝謝bluefeet。您的答案正確,但我也需要顯示第4列和第5列,而不管它們是否有值或根本沒有值。 – matley