我正在尝试总结查询的输出,但正在苦苦挣扎。下面的查询检查了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、传真 10 = 1、传真总计 = 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;