2012-09-11 75 views
2

我需要一個SQL查詢來合併我在我的表上不同列上的所有數字,並找到它們出現的總和。Number Frequencies

我的表結構是這樣的

id | Pick1 | Pick2 | Pick3 | Pick4 | Pick5 | Pick6 | 
---------------------------------------------------- 
1 | 1  | 23 | 56 | 56 | 78 | 89 | 
---------------------------------------------------- 
2 | 9  | 49 | 90 | 56 | 78 | 89 | 
---------------------------------------------------- 
3 | 2  | 65 | 56 | 56 | 78 | 89 | 
---------------------------------------------------- 
4 | 1  | 23 | 23 | 56 | 78 | 89 | 

預期結果

Number | Frequency 
------------------- 
    23 | 5 
------------------- 
    56 | 7 
------------------- 
    89 | 4 
.... 

誰能幫助?

回答

0

您需要在子查詢中使用UNION ALL來合併所有記錄。試試這個,

SELECT x.a `Number`, 
     COUNT(x.a) `Frequency` 
FROM 
(
    SELECT Pick1 a 
    FROM TableNAME 
    UNION ALL 
    SELECT Pick2 a 
    FROM TableNAME 
    UNION ALL 
    SELECT Pick3 a 
    FROM TableNAME 
    UNION ALL 
    SELECT Pick4 a 
    FROM TableNAME 
    UNION ALL 
    SELECT Pick5 a 
    FROM TableNAME 
    UNION ALL 
    SELECT Pick6 a 
    FROM TableNAME 
) x 
GROUP BY x.a 
0
SELECT pick AS `Number`, 
     COUNT(1) AS Frequency 
FROM(
    SELECT Pick1 AS pick 
    FROM table_name 
    UNION ALL 
    SELECT Pick2 AS pick 
    FROM table_name 
    SELECT Pick3 AS pick 
    FROM table_name 
    SELECT Pick4 AS pick 
    FROM table_name 
    SELECT Pick5 AS pick 
    FROM table_name 
    SELECT Pick6 AS pick 
    FROM table_name 
    ) a 
GROUP BY a.pick; 
0

這會容易得多,如果你能重新整理表格到類似下面的struture:

id | pick | nr 
------------------ 
1 1  1 
1 2  23 
1 3  56 

在這樣的表格,你可以很容易分組並統計數字。 在你的項目中可以改變這種表結構嗎?

或者,如果不可行,則可以創建一個輔助視圖,它將數據排列在此結構中,然後將此結果用於進一步處理。這種觀點可以通過使用6個選擇語句的聯合來構建。如果您需要進一步的幫助,請告訴我。