SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Mar 2005
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question MySQL Conditional Count

    I am having trouble running this conditional count:

    SELECT
    COUNT(CASE WHEN purchase.status = 'complete' THEN purchase.purchase_id ELSE 0 END) AS num_completed_purchases,
    SUM(CASE WHEN purchase.status = 'complete' THEN purchase.price ELSE 0 END) AS total_sales_revenue
    FROM products
    LEFT JOIN purchases ON products.product_id = purchases.product_id
    GROUP BY products.product_id


    The SUM() is working fine but the COUNT() doesn't seem to give me the desired result. If a product has 2 associated records in the purchases table, 1 'complete' and 1 not, then num_completed_purchases should equal 1. However as long as the status = 'complete' condition is met in one row then all rows for that product are counted (num_completed_purchases is returned as 2). However only 'completed' purchases are added to the SUM() of total_sales_revenue.

    What am I doing wrong? Why does it COUNT() all or none?

    Thanks in advance.

  2. #2
    Chessplayer kleineme's Avatar
    Join Date
    Apr 2004
    Location
    Germany
    Posts
    608
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi,

    COUNT(*) counts all records, COUNT(column) counts all records where column is not NULL. So you may try this:

    COUNT(CASE WHEN purchase.status = 'complete' THEN 1 ELSE NULL END) AS num_completed_purchases,
    Never ascribe to malice,
    that which can be explained by incompetence.
    Your code should not look unmaintainable, just be that way.

  3. #3
    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)
    kleineme's solution works --

    COUNT(CASE WHEN purchase.status = 'complete'
    THEN 1 ELSE NULL END)

    so does this --

    COUNT(CASE WHEN purchase.status = 'complete'
    THEN 937 ELSE NULL END)

    and so does this (which is what i think you meant in your original query) --

    SUM(CASE WHEN purchase.status = 'complete'
    THEN 1 ELSE 0 END)

    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

  4. #4
    SitePoint Member
    Join Date
    Mar 2005
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Thanks

    Thanks Both for your replies. The SUM (CASE WHEN condition THEN 1 ELSE 0 END) works well, as does the COUNT (CASE WHEN condition THEN 1 ELSE NULL END). I didn't realise that COUNT ignores NULL rows but that does make sense. I was too busy counting like a human.


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
  •