0

我有一张像

CREATE TABLE sales
    (`id` int, `date` date, `amount` int(4))
;

insert into sales values (1, '2012-09-01', 200),
                         (2, '2012-09-01', 300),
                         (3, '2012-09-02', 400),
                         (4, '2012-09-02', 500),
                         (5, '2012-09-02', 600)

我希望检索显示今天销售额和昨天销售额的行

Date             Today Total sales   Yesterday Sales
2012-09-02       1500                500

尝试使用类似的东西

SELECT id, date, sum(amount) FROM sales
GROUP BY date;

但它会明智地返回销售日。我知道可以以编程方式完成,但是有没有更好的方法可以直接从数据库中检索它?

sqlfiddle

4

3 回答 3

2
SELECT id, date(now()) as `date`, 
      SUM(IF(date(`date`) = date(now()), `amount`, 0)) as TodayTotalSales,
      SUM(IF(date(`date`) < date(now()), `amount`, 0)) as OtherDaySales
FROM sales;

http://sqlfiddle.com/#!2/0ef6a/18

于 2012-10-18T02:54:36.507 回答
0

您会得到它,因为Id每条记录都不同。你现在有两个选择:

  1. 不要检索 Id 并编写如下查询:

    SELECT date, sum(amount) FROM sales
    GROUP BY date;
    
  2. 使用带有子查询的连接

    SELECT a.ID, a.date, b.amount
    FROM sales a, (SELECT date, sum(amount) amount FROM sales
                   GROUP BY date) b
    WHERE a.date = b.date;
    

    请注意:在选项 2 中,第二列和第三列将在一天内为每个 id 重复相同的值。

于 2012-10-18T02:44:15.837 回答
0
SELECT date, sum(amount), yestersales 
FROM sales AS s1, 
    (SELECT sum(amount) as yestersales, ADDDATE(date, 1) AS yesterdate 
        FROM sales GROUP BY date) AS s2
WHERE s1.date = s2.yesterdate
GROUP BY date;

会做你想做的事,但我不认为它真的很有效。我会亲自用代码来做。

由于您是按日期分组的,因此在这里选择 ID 并没有多大意义。

于 2012-10-18T02:55:41.400 回答