我想總結一個查詢的輸出,但我正在掙扎。下面的查詢檢查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;
你說的錯誤是什麼意思? –
@Jack - 對不起,我的意思是它不起作用,只是給我一個語法錯誤 – btongeorge