Complicated COUNT() Command. Confused!

Discussion in 'Databases' started by Masterful, Feb 20, 2009.

  1. #1
    Any help will be very much appreciated.

    Here's my query:

    "SELECT tblmake.make, tblmake.url, COUNT(tblmodel.modelid) AS model_count
    FROM tblmake
    LEFT JOIN tblmodel ON tblmake.makid = tblmodel.makeid
    GROUP BY tblmake.makid
    ORDER BY tblmake.make ASC";
    Code (markup):
    How do I incorporate the following condition in the COUNT:

    (adddate >= CURDATE() OR adddate is NULL)
    Code (markup):
    In other words, how do I get it to count only the tblmodel.modelids whose adddates are greater or equal to the current date or whose tblmodel.modelids are NULL?
     
    Masterful, Feb 20, 2009 IP
  2. gnp

    gnp Peon

    Messages:
    137
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #2
    well since the adddate is on the joined table you could add this filter on the join

    
    SELECT tblmake.make, tblmake.url, COUNT(tblmodel.modelid) AS model_count
    FROM tblmake
    LEFT JOIN tblmodel ON tblmake.makid = tblmodel.makeid
    AND (tblmodel.adddate >= CURDATE() OR isnull(tblmodel.adddate,0) = 0)
    GROUP BY tblmake.makid
    ORDER BY tblmake.make ASC
    
    Code (sql):
    (the above isnull is mssql syntax..)
     
    gnp, Feb 20, 2009 IP
  3. Masterful

    Masterful Well-Known Member

    Messages:
    1,653
    Likes Received:
    28
    Best Answers:
    0
    Trophy Points:
    140
    #3

    Thanks for the effort, but that doesn't work. I've already tried it. I have to make it a part of the COUNT function somehow.

    Anyone know how?
     
    Masterful, Feb 20, 2009 IP
  4. gnp

    gnp Peon

    Messages:
    137
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Not sure why it does not work...
    Error ? or wrong results ?

    Try another more explicit way
    
    SELECT 
    	tblmake.make, 
    	tblmake.url, 
    	( 
    		SELECT 
    			count(modelid) 
    		FROM 
    			tblmodel 
    		WHERE 
    			(adddate >= CURDATE() OR adddate is null) 
    			AND 
    			tblmake.makeid = tblmodel.makeid 
    		GROUP BY 
    			tblmodel.makeid 
    	) AS model_count
    FROM 
    	tblmake 
    ORDER BY 
    	tblmake.make ASC
    
    Code (sql):
    a question: you sure you want the models that were made after today ? (future models ?) (had to ask :) )

    hope this does the trick
     
    gnp, Feb 20, 2009 IP
    Masterful likes this.
  5. Masterful

    Masterful Well-Known Member

    Messages:
    1,653
    Likes Received:
    28
    Best Answers:
    0
    Trophy Points:
    140
    #5
    Thanks, Gnp! It worked. :)

    One reputation point for you! ;)
     
    Masterful, Feb 20, 2009 IP
  6. gnp

    gnp Peon

    Messages:
    137
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Glad it worked !

    thanks for the rep :)
     
    gnp, Feb 21, 2009 IP