SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Thread: Order by count

Hybrid View

  1. #1
    SitePoint Evangelist
    Join Date
    Jan 2005
    Location
    UK
    Posts
    539
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Order by count

    I have a query that orders results by the count of another table:

    "SELECT table1.*, COUNT(table2.id) AS rev_count FROM table1
    LEFT JOIN table2 ON table1.name = table2.name
    WHERE table1.active = 1 AND table1.city='$city'
    GROUP BY table1.name
    ORDER BY rev_count DESC";

    How do you add a condition (ie WHERE active=1) to just the "COUNT(table2.id) AS rev_count" part of the query?

  2. #2
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,215
    Mentioned
    58 Post(s)
    Tagged
    3 Thread(s)
    Code:
    SELECT table1.*
         , COUNT(table2.id) AS rev_count 
      FROM table1 
    LEFT 
      JOIN table2 
        ON table2.name = table1.name 
       AND table2.active = 1 
     WHERE table1.active = 1 
       AND table1.city = '$city'
    GROUP 
        BY table1.name
    ORDER 
        BY rev_count DESC
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

  3. #3
    SitePoint Evangelist
    Join Date
    Jan 2005
    Location
    UK
    Posts
    539
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ah yes of course! Cheers!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •