当前位置:Gxlcms > 数据库问题 > SQL 从查询结果里查询

SQL 从查询结果里查询

时间:2021-07-01 10:21:17 帮助过:104人阅读

-%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:
SQL 教程

case when then else end 学习能够看以下这篇博文:
sql case when then else end 使用方法

SQL 从查询结果里查询

标签:incr   简单的   into   cas   title   alt   教程   group by   图片   

人气教程排行