MySQL总和基于先前按日期选择

时间:2013-01-22 13:56:28

标签: mysql

我有一个非常规范化的MySQL表,其中包含以下值:

customer_ID | date | score | sale

当我评分“购买体验”时,我想根据他的最后得分检查每位顾客的总销售价值。我不介意以前的分数,只是最后一分。

让我说我有:

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

客户购买分数>的结果5应该是:

num of customers | total sale values  
2                | 65

如何创建此类查询?

编辑:

我想知道的是,客户在购买中花了多少钱,而只是最后得分大于5的客户。

1 个答案:

答案 0 :(得分: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

更加简化,

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