-1

我有如下表

name  price  date

soap    10    2013-09-18
soap    10    2013-09-18
pens     8    2013-09-18
deos     7    2013-09-18
book    13    2013-09-17
book    13    2013-09-17
soap    10    2013-09-17
pens     8    2013-09-17

根据上述数据,我想计算每件商品的总销售额排名(基于今天和前一天的价格如下。

姓名总销售日期今天排名前一天排名

肥皂 20 2013-09-18 1 2
笔 8 2013-09-18 2 2
deos 7 2013-09-18 3 -

如果今天的物品在昨天没有退出,那么它在前一天的排名应该是空的。

4

2 回答 2

1
SELECT a.name,
       a.todaysales,
       a.date,
       a.rank AS ranktoday,
       b.rank AS rankyesterday
FROM
  (SELECT name, sum(price) AS todaysales, date, @n := @n + 1 AS rank
   FROM TABLE , (SELECT @n := 0) alias
   WHERE date=curdate() group by 1  order by count(*))a
INNER JOIN
  (SELECT name, sum(price) AS todaysales, date, @n := @n + 1 AS rank
   FROM TABLE , (SELECT @n := 0) alias
   WHERE date=curdate() - interval 1 DAY group by 1  order by count(*))b ON a.name=b.name
于 2013-09-20T12:12:18.950 回答
1

您将不得不使用子选择、日期间隔、一些变量、一个案例和一些脑力劳动。将所有这些混合在一起,你会得到这样的东西:

SELECT today.*,
       CASE 
         WHEN yesterday.yesterdayrank IS NULL THEN '-' 
         ELSE yesterday.yesterdayrank 
       END
FROM (SELECT @i:=@i +1 AS todayrank,
             name,
             SUM(price) AS price
      FROM test,
           (SELECT @i:= 0) AS foo
      WHERE createdate = DATE (NOW()) - INTERVAL 2 DAY
      GROUP BY name
      ORDER BY todayrank) today
  LEFT JOIN (SELECT @j:= @j +1 AS yesterdayrank,
                    name,
                    SUM(price) AS price
             FROM test,
                  (SELECT @j:= 0) AS bar
             WHERE createdate = DATE (NOW()) - INTERVAL 3 DAY
             GROUP BY name
             ORDER BY yesterdayrank) yesterday ON today.name = yesterday.name

我希望这有帮助。

于 2013-09-20T12:12:36.973 回答