Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

COUNT number of returned rows 1

Status
Not open for further replies.

slowfish

Programmer
Aug 21, 2009
28
GB
Hi

My query returns all the records of "active" London customers who have ordered within the past year. I also need to know how many customers, but where do I put the COUNT function?

SELECT *, MAX(customers_orders.date) AS maxdate,
customers.id AS refid,

FROM customers

LEFT JOIN customers_orders ON customers.id = customers_orders.custid

WHERE archived = 'no' AND city = 'London'

GROUP BY customers.id

HAVING maxdate >= DATE_SUB(NOW(),INTERVAL 1 YEAR)

Thanks in advance
slowfish
 
the answer is to use whatever function is available in your application language for this purpose (in php i believe it's called mysql_num_rows() or something similar)

failing that, just run another query, putting your original query inside a simple SELECT COUNT(*)
Code:
SELECT COUNT(*) AS number_of_customers
  FROM ( SELECT /* no dreaded, evil "select star" */
                MAX(customers_orders.date) AS maxdate     
              , customers.id AS refid /* no comma */
           FROM customers
         INNER    /* not LEFT */
           JOIN customers_orders 
             ON customers_orders.custid = customers.id
          WHERE customers.archived = 'no' /* qualify your columns */
            AND customers.city = 'London' /* qualify your columns */
         GROUP 
             BY customers.id
         HAVING maxdate >= CURRENT_DATE - INTERVAL 1 YEAR
       ) AS q
:)

r937.com | rudy.ca
Buy my new book Simply SQL from Amazon
 
That's great, thanks very much. The query inside the query worked. I'm using Perl but not sure what the equivalent of mysql_num_rows() is. Any ideas?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top