51Testing软件测试论坛

标题: SQL 从查询结果里查询 [打印本页]

作者: 感悟时分    时间: 2018-4-12 16:30
标题: SQL 从查询结果里查询
有orders表:
[attach]113341[/attach]

我想要从从表中查出每天电动车和手机各自的销售总额。这个需求还是蛮简单的,只需要根据createtime和pro
duct 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
1
查询结果如下:
[attach]113342[/attach]

这个结果确实满足了我的需求,但是存在一个问题,就是当天数多了的时候,会看得我头晕眼花的。如果查
询结果是下面这个样子,我想看起来会舒服得多:
[attach]113343[/attach]
对于如何直接从表中查询出这样的结果,我是一点想法都没有,但是,我却知道如何从上一个SQL语句的
查询结果中查询从而得到想要的结果,下面是我写的SQL语句:

  1. SELECT origintable.cr,
  2. SUM(CASE WHEN origintable.product = "电动车" THEN origintable.total ELSE 0 END) "电动车",
  3. SUM(CASE WHEN origintable.product = "手机" THEN origintable.total ELSE 0 END) "手机"
  4. FROM (SELECT DATE_FORMAT( createtime, "%Y-%m-%d" ) AS cr, product, SUM(price) AS total
  5. FROM orders GROUP BY DATE_FORMAT(createtime, "%Y-%m-%d"), product) AS origintable
  6. GROUP BY origintable.cr
复制代码


如果大家想亲自试一试,可以用下面的SQL语句创建orders表和向表中插入数据:

  1. create table orders(
  2. id int PRIMARY KEY auto_increment,
  3. product VARCHAR(64) null,
  4. price DOUBLE null,
  5. createtime DATETIME
  6. )

  7. INSERT INTO orders (orders.product, orders.price, orders.createtime) VALUES ("电动车", 50, NOW());
  8. INSERT INTO orders (orders.product, orders.price, orders.createtime) VALUES ("手机", 60, NOW());
  9. INSERT INTO orders (orders.product, orders.price, orders.createtime) VALUES ("电动车", 50, NOW());
  10. INSERT INTO orders (orders.product, orders.price, orders.createtime) VALUES ("手机", 60, NOW());
  11. INSERT INTO orders (orders.product, orders.price, orders.createtime) VALUES ("电动车", 50, "2016-04-14 22:16:11");
  12. INSERT INTO orders (orders.product, orders.price, orders.createtime) VALUES ("手机", 60, "2016-04-14 22:16:11");
  13. INSERT INTO orders (orders.product, orders.price, orders.createtime) VALUES ("电动车", 50, "2016-04-14 22:16:11");
  14. INSERT INTO orders (orders.product, orders.price, orders.createtime) VALUES ("手机", 60, "2016-04-14 22:16:11");
复制代码

如果大家有其它方式实现本文的需求,欢迎留言。

提示:
本文所有SQL语句均根据MySQL数据库编写。


作者: chenyangyang1    时间: 2018-4-12 18:11
正在了解

作者: Ta因为帅居然    时间: 2018-5-3 19:59
select create_time,sum(if(product ='电动车',price,0))as '电动车当日销售额',sum(if(product ='手机',price,0))as '当日手机销售额'from table group by create_time
作者: testing444555    时间: 2018-5-22 15:04

作者: jinsolo823    时间: 2018-6-7 11:16
select createtime,sum(if(product ='电动车',price,0))as '电动车当日销售额',sum(if(product ='手机',price,0))as '当日手机销售额'from orders group by createtime;

作者: RedQA    时间: 2018-6-14 15:57





欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) Powered by Discuz! X3.2