0

I have a not-very-normalized MySQL table with the following values:

customer_ID | date | score | sale

As I am scoring the "purchase experience", I would like to check the total sale value for each customer based on his last score. I do not mind about previous scores, just about last one.

Let's say I have:

customer_ID | date      | score | sale  
a           | yesterday | 3     | 10  
a           | today     | 6     | 35  
b           | today     | 10    | 20  
c           | yesterday | 4     | 5  

The result for customers purchases with score > 5 should be:

num of customers | total sale values  
2                | 65

Any idea of how to create such query?

Edit:

What I want to know is how much has a customer spent in purchases in total, but just on customers whose last score was bigger than 5.

8
  • What have you tried? See ask advice, please.
    – John Conde
    Commented Jan 22, 2013 at 13:57
  • Inadequate explanation. Try to improve it!
    – Strawberry
    Commented Jan 22, 2013 at 13:59
  • 1
    when you say yesterday is it really a literal string value yesterday?
    – John Woo
    Commented Jan 22, 2013 at 13:59
  • Hi, not yesterday literally. I wrote that to make it easier to understand. What I want to know is how much has a customer spent in purchases in total, but just on customers whose last score was bigger than 5.
    – fedorqui
    Commented Jan 22, 2013 at 14:04
  • one more thing for example customer a has a record dated 2 days before with a score of 6 and sale of 15, what will be the result? and how was total sale values calculated?
    – John Woo
    Commented Jan 22, 2013 at 14:08

1 Answer 1

1
SELECT  COUNT(DISTINCT aa.customer_ID) `num of customers`,
        SUM(aa.sale) `total sale values `
FROM    table1 aa
        INNER JOIN
        (
            SELECT  a.customer_ID
            FROM    table1  a
                    INNER JOIN
                    (
                        SELECT  customer_ID, max(date) max_date
                        FROM    table1
                        GROUP   BY customer_ID
                    ) b ON a.customer_ID = b.customer_ID AND
                            a.date = b.max_date AND a.score > 5
        ) final ON aa.customer_ID = final.customer_ID

much more simplified,

SELECT  COUNT(DISTINCT c.customer_ID) `num of customers`,
        SUM(c.sale) `total sale values `
FROM    table1  a
        INNER JOIN
        (
            SELECT  customer_ID, max(date) max_date
            FROM    table1
            GROUP   BY customer_ID
        ) b ON a.customer_ID = b.customer_ID AND
                a.date = b.max_date AND a.score > 5
        INNER JOIN table1 c
            ON a.customer_ID = c.customer_ID
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.