SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Guru
    Join Date
    Sep 2004
    Location
    Provo, UT
    Posts
    865
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Combining two different types of count

    What is the best way to combine these two queries into one?

    Code:
    select count(*) as scheduled from notifications where date_format(dateScheduled, '%Y-%m-%d')  = curdate();
    
    
    select count(*) as delivered from notifications where date_format(dateScheduled, '%Y-%m-%d')  = curdate() and dateSent is not null;
    Thanks!
    Convert your dollars into silver coins. www.convert2silver.com

  2. #2
    SitePoint Guru
    Join Date
    Sep 2004
    Location
    Provo, UT
    Posts
    865
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Nevermind. I think this is working good for me:

    Code:
    select 
    	
    	(select count(*) from notifications where date_format(dateScheduled, '%Y-%m-%d')  = curdate()) as scheduled,
    
    
    	(select count(*) from notifications where date_format(dateScheduled, '%Y-%m-%d')  = curdate() and dateSent is not null) as delivered
    
    
    FROM notifications group by scheduled, delivered;
    Convert your dollars into silver coins. www.convert2silver.com

  3. #3
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,323
    Mentioned
    63 Post(s)
    Tagged
    3 Thread(s)
    Quote Originally Posted by busboy View Post
    Code:
     where date_format(dateScheduled, '%Y-%m-%d')  = curdate()
    while that does work, it's not the most efficient approach

    a simpler method is this --
    Code:
     WHERE DATE(dateScheduled) = CURRENT_DATE()
    however, this too suffers from an efficiency problem

    using a function on a table column pretty much rules out index optimization, and the database optimizer will often just do a table scan

    here is a much better approach that will utilize an index on the column --
    Code:
     WHERE dateScheduled >= CURRENT_DATE()
       AND dateScheduled  < CURRENT_DATE() + INTERVAL 1 DAY
    you also used two complete passes of the data, whereas you really only need one --
    Code:
    SELECT COUNT(*) AS scheduled
         , COUNT(dateSent) AS delivered
      FROM notifications 
     WHERE dateScheduled >= CURRENT_DATE()
       AND dateScheduled  < CURRENT_DATE() + INTERVAL 1 DAY
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

  4. #4
    SitePoint Guru
    Join Date
    Sep 2004
    Location
    Provo, UT
    Posts
    865
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Thanks again Rudy!
    Convert your dollars into silver coins. www.convert2silver.com


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
  •