1

假设我有一个这样的表:

编号 | 日期 | 客户 | 销售

并希望为每个客户选择:

  • 购买次数
  • 上次购买价值
  • 购买总量,当它具有正值时

使用此表定义:

CREATE TABLE sales (
    id int auto_increment primary key, 
    dates date,
    customer int,
    sale int
);

而这个数据:

INSERT INTO sales
    (dates, customer, sale)
VALUES
    ('2012-01-01', 1, 2),
    ('2012-02-01', 1, 8),
    ('2012-03-01', 2, 1),
    ('2012-04-01', 2, 7),
    ('2012-05-01', 2, -5),
    ('2012-06-01', 1, 5)

我的结果应该是:

客户 | 销售 | 最后销售
1 3 5
2 3 7

我无法弄清楚如何获得它。我已经达到了这个:

SELECT s.customer, COUNT(s.sale) total_sales, last_sale FROM sales AS s
JOIN
  (SELECT customer, sale last_sale FROM sales GROUP BY customer ORDER BY dates DESC) AS t
  ON t.customer=s.customer
GROUP BY s.customer

但它不起作用。关于如何获取这些数据的任何想法?

所有代码都在SQL 小提琴中

4

2 回答 2

3

试试这个

SELECT a.customer, count(a.sale), max_sale
FROM sales a
INNER JOIN (SELECT customer, sale max_sale 
            from sales x where dates = (select max(dates) 
                                        from sales y 
                                        where x.customer = y.customer
                                        and y.sale > 0
                                       )

           )b
ON a.customer = b.customer
GROUP BY a.customer, max_sale;

SQL 演示

于 2013-02-19T15:59:06.103 回答
1
SELECT a.customer, 
       COUNT(a.sale) total_sales,
       c.sale
FROM   sales a
       INNER JOIN
        (
          SELECT  a.*
          FROM    sales a
                  INNER JOIN
                  (
                    SELECT  Customer, MAX(Dates) max_date
                    FROM    sales
                    WHERE   sale > 0
                    GROUP   BY Customer
                  ) b ON a.customer = b.customer AND
                          a.dates = b.max_date
        ) c ON a.customer = c.customer
GROUP  BY a.customer, c.sale
于 2013-02-19T15:59:59.490 回答