Note that there are some explanatory texts on larger screens.

plurals
  1. POSummarising output from MySQL query
    primarykey
    data
    text
    <p>I am trying to summarize the output of a query but am struggling. The query below checks the fax_authorized table and generates a summary of extensions with email addresses against them. </p> <p>I have the following query:</p> <pre><code>SELECT extended_number, IF(COUNT(extension_id)&lt;5,1,0) AS 'fax5', IF(COUNT(extension_id)&gt;5 AND COUNT(extension_id)&lt;11,1,0) AS 'fax10', IF(COUNT(extension_id)&gt;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; </code></pre> <p>The output looks like this:</p> <pre><code>+-----------------+------+-------+--------+-----------+ | 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 | +-----------------+------+-------+--------+-----------+ </code></pre> <p>What I would like is to summarize this data based on LEFT(extended_number,4) so that for example 0139 above would have fax5=2, fax10=1, fax_total=9.</p> <p>I have tried this, which doesn't work:</p> <pre><code>SELECT extended_number, SUM(IF(COUNT(extension_id)&lt;5,1,0)) AS 'fax5', SUM(IF(COUNT(extension_id)&gt;5 AND COUNT(extension_id)&lt;11,1,0)) AS 'fax10', SUM(IF(COUNT(extension_id)&gt;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); </code></pre> <p>Edit: I used the answer of Saharsh Shah below to solve this issue, but hit another one which I thought was worth adding. I tried to create a view from his nested subquery solution but was unable to, as subqueries aren't allowed in views. So I created two related views as follows:</p> <pre><code>CREATE VIEW vw_xoom_faxdetail AS SELECT LEFT(extended_number,4) client_id, IF(COUNT(extension_id)&lt;5,1,0) AS 'fax5', IF(COUNT(extension_id)&gt;5 AND COUNT(extension_id)&lt;11,1,0) AS 'fax10', IF(COUNT(extension_id)&gt;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; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload