有orders表:
我想要从从表中查出每天电动车和手机各自的销售总额。这个需求还是蛮简单的,仅仅须要依据createtime和product group by即可了。以下是我写的SQL语句:
SELECT DATE_FORMAT( createtime, "%Y-%m-%d" ) cr, product, SUM(price) total FROM orders GROUP BY DATE_FORMAT(createtime, "%Y-%m-%d"), product
查询结果例如以下:
这个结果确实满足了我的需求,可是存在一个问题。就是当天数多了的时候,会看得我头晕眼花的。假设查询结果是以下这个样子,我想看起来会舒服得多:
对于怎样直接从表中查询出这种结果,我是一点想法都没有,可是,我却知道怎样从上一个SQL语句的查询结果中查询从而得到想要的结果。以下是我写的SQL语句:
SELECT origintable.cr,
SUM(CASE WHEN origintable.product = "电动车" THEN origintable.total ELSE 0 END) "电动车",
SUM(CASE WHEN origintable.product = "手机" THEN origintable.total ELSE 0 END) "手机"
FROM (SELECT DATE_FORMAT( createtime, "%Y-%m-%d" ) AS cr, product, SUM(price) AS total
FROM orders GROUP BY DATE_FORMAT(createtime, "%Y-%m-%d"), product) AS origintable
GROUP BY origintable.cr
假设大家想亲自试一试,能够用以下的SQL语句创建orders表和向表中插入数据:
create table orders(
id int PRIMARY KEY auto_increment,
product VARCHAR(64) null,
price DOUBLE null,
createtime DATETIME
)
INSERT INTO orders (orders.product, orders.price, orders.createtime) VALUES ("电动车", 50, NOW());
INSERT INTO orders (orders.product, orders.price, orders.createtime) VALUES ("手机", 60, NOW());
INSERT INTO orders (orders.product, orders.price, orders.createtime) VALUES ("电动车", 50, NOW());
INSERT INTO orders (orders.product, orders.price, orders.createtime) VALUES ("手机", 60, NOW());
INSERT INTO orders (orders.product, orders.price, orders.createtime) VALUES ("电动车", 50, "2016-04-14 22:16:11");
INSERT INTO orders (orders.product, orders.price, orders.createtime) VALUES ("手机", 60, "2016-04-14 22:16:11");
INSERT INTO orders (orders.product, orders.price, orders.createtime) VALUES ("电动车", 50, "2016-04-14 22:16:11");
INSERT INTO orders (orders.product, orders.price, orders.createtime) VALUES ("手机", 60, "2016-04-14 22:16:11");
假设大家有其他方式实现本文的需求,欢迎留言。
提示:
本文全部SQL语句均依据MySQL数据库编写。
推荐:
SQL基础知识学习能够去w3school:
case when then else end 学习能够看以下这篇博文:
sql case when then else end 使用方法
时间: 2024-11-12 02:41:26