2012-12-06 110 views
1

我想總結一個查詢的輸出,但我正在掙扎。下面的查詢檢查fax_authorized表,並根據他們的電子郵件地址生成擴展摘要。總結來自MySQL查詢的輸出

我有以下查詢:

SELECT extended_number, IF(COUNT(extension_id)<5,1,0) AS 'fax5', 
    IF(COUNT(extension_id)>5 AND COUNT(extension_id)<11,1,0) AS 'fax10', 
    IF(COUNT(extension_id)>10,1,0) AS 'fax10+', COUNT(extension_id) AS 'fax_total' 
FROM fax_authorized fa, extension e 
WHERE fa.extension_id = e.id 
GROUP BY extended_number; 

輸出看起來是這樣的:

+-----------------+------+-------+--------+-----------+ 
| extended_number | fax5 | fax10 | fax10+ | fax_total | 
+-----------------+------+-------+--------+-----------+ 
| 0009*004  | 1 |  0 |  0 |   1 | 
| 0139*601  | 0 |  1 |  0 |   6 | 
| 0139*743  | 1 |  0 |  0 |   2 | 
| 0139*996  | 1 |  0 |  0 |   1 | 
+-----------------+------+-------+--------+-----------+ 

我想什麼是總結基礎上離開了這個數據(extended_number,4),以便爲上面的示例0139將具有fax5 = 2,fax10 = 1,fax_total = 9。

我曾經嘗試這樣做,不工作:

SELECT extended_number, SUM(IF(COUNT(extension_id)<5,1,0)) AS 'fax5', 
    SUM(IF(COUNT(extension_id)>5 AND COUNT(extension_id)<11,1,0)) AS 'fax10', 
    SUM(IF(COUNT(extension_id)>10,1,0)) AS 'fax10+', 
    COUNT(LEFT(extension_id,4)) AS 'fax_total' 
FROM fax_authorized fa, extension e 
WHERE fa.extension_id = e.id 
GROUP BY LEFT(extended_number,4); 

編輯:我用Saharsh沙阿回答下面來解決這個問題,可是撞到了另外一個,我認爲是值得加入。我試圖從他的嵌套子查詢解決方案創建一個視圖,但無法執行,因爲視圖中不允許使用子查詢。所以,我創建了兩個相關的觀點如下:

CREATE VIEW vw_xoom_faxdetail AS 
    SELECT LEFT(extended_number,4) client_id, 
    IF(COUNT(extension_id)<5,1,0) AS 'fax5', 
    IF(COUNT(extension_id)>5 AND COUNT(extension_id)<11,1,0) AS 'fax10', 
    IF(COUNT(extension_id)>10,1,0) AS 'fax10plus', 
    COUNT(extension_id) AS 'fax_total' 
FROM fax_authorized fa, extension e WHERE fa.extension_id = e.id 
GROUP BY client_id; 

CREATE VIEW vw_xoom_fax AS 
SELECT client_id, SUM(fax5) fax5, SUM(fax10) fax10, 
    SUM(fax10plus) 'fax10+', SUM(fax_total) fax_total 
FROM vw_xoom_faxdetail 
GROUP BY client_id; 
+0

你說的錯誤是什麼意思? –

+0

@Jack - 對不起,我的意思是它不起作用,只是給我一個語法錯誤 – btongeorge

回答

0

試試這個:

SELECT extended_number, SUM(fax5) fax5, SUM(fax10) fax10, SUM(fax10plus) 'fax10+', SUM(fax_total) fax_total 
FROM (SELECT LEFT(extended_number,4) extended_number, IF(COUNT(extension_id)<5,1,0) AS 'fax5', 
      IF(COUNT(extension_id)>5 AND COUNT(extension_id)<11,1,0) AS 'fax10', 
     IF(COUNT(extension_id)>10,1,0) AS 'fax10plus', COUNT(extension_id) AS 'fax_total' 
     FROM fax_authorized fa, extension e WHERE fa.extension_id = e.id 
     GROUP BY extended_number) AS A 
GROUP BY extended_number; 
+0

工程太棒了!謝謝。所以我正確理解這一點,您的解決方案是將我的聚合查詢嵌套在另一箇中?我在內部和外部查詢中使用extended_number時感到困惑,實際上,在外部查詢中,它只是extended_number的左邊4個字符。 – btongeorge

+0

我現在有另一個問題 - 我想從這個查詢創建一個視圖用於我的數據庫,但是我得到一個錯誤:錯誤1349(HY000):視圖的SELECT包含FROM子句中的子查詢 – btongeorge

+0

原來的子查詢aren在視圖定義中不允許 - 已編輯該問題以顯示我如何創建兩個相關的視圖定義。 – btongeorge