0

我有一个不是很规范化的 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 的客户身上。

4

1 回答 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

更加简化,

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
于 2013-01-22T14:14:12.017 回答