在1个结果集中组合多个列

时间:2012-10-18 02:38:36

标签: mysql sql

我有一张像

这样的表格
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;

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

sqlfiddle

3 个答案:

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

答案 1 :(得分: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重复相同的值。

答案 2 :(得分: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并不是很有意义。