我试图总结一个查询的输出,但我正在努力。下面的查询检查fax_authorized表并生成带有电子邮件地址的扩展摘要。
我有以下查询:
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 |
+-----------------+------+-------+--------+-----------+
我想要的是根据LEFT(extended_number,4)总结这些数据,以便例如上面的0139将传真5 = 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 Shah的答案来解决这个问题,但打了另一个我认为值得补充的问题。我尝试从他的嵌套子查询解决方案创建一个视图,但由于视图中不允许子查询,因此无法进行。所以我创建了两个相关的视图如下:
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)
试试这个:
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;