简体   繁体   English

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

[英]Combining multiple columns in 1 resultset

I have a table like 我有一张桌子

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)

I wish to retrieve a row showing the sales for today, and the sales for yesterday 我希望检索一行显示今天的销售额和昨天的销售额

like 喜欢

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

Tried using something like 尝试用类似的东西

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

But it returns the sales day wise. 但它明智地回报了销售日。 I understand that can be done programmatically, but is there a better way to directly retrieve it from the DB? 我知道可以通过编程方式完成,但有没有更好的方法直接从数据库中检索它?

sqlfiddle sqlfiddle

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 http://sqlfiddle.com/#!2/0ef6a/18

You are getting that because Id is different for each record. 你得到的是因为每个记录的Id不同。 You have two option now: 你现在有两个选择:

  1. Don't retrieve Id and write query like: 不要检索Id和写入查询,如:

     SELECT date, sum(amount) FROM sales GROUP BY date; 
  2. Use a join with subquery 使用子查询的连接

     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; 

    Please Note: In option 2, second and third columns will be repeating with same value for each id within a day. 请注意:在选项2中,第二列和第三列将在一天内为每个ID重复相同的值。

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;

Will do what you want, but it's not really very efficient, I don't think. 会做你想做的事,但我认为这不是非常有效率。 I would personally do it in code. 我个人会在代码中这样做。

Selecting the ID doesn't really make much sense here since you're grouping by date. 由于您按日期分组,因此选择ID在这里没有多大意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM