With Orders table:
I want to find out from the table the total sales of electric cars and mobile phones each day. This requirement is quite simple, and only needs to be based on Createtime and product group by. Here is the SQL statement I wrote:
"%Y-%m-%d""%Y-%m-%d"), product
Query results such as the following:
The result really met my needs, but there was a problem. It is the day when the number is more, will see me dizzy. Let's say the query results look something like this, and I want to look much more comfortable:
I have no idea how to query the results directly from the table, but I know how to query from the query results of the previous SQL statement to get the desired results. Here is the SQL statement I wrote:
SELECTORIGINTABLE.CR,SUM( Case whenOrigintable.product ="Electric Car" ThenOrigintable.totalELSE 0 END)"Electric Car",SUM( Case whenOrigintable.product ="mobile" ThenOrigintable.totalELSE 0 END)"mobile" from(SELECTDate_format (Createtime,"%y-%m-%d") asCR, Product,SUM(Price) asTotal fromOrdersGROUP byDate_format (Createtime,"%y-%m-%d"), product) asOrigintableGROUP byOrigintable.cr
If you want to try it yourself, you can create an Orders table and insert data into a table with the following SQL statements:
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 ("EV" , and Now ()); INSERT into orders (Orders.product, Orders.price, orders.createtime) VALUES ("Phone" , and Now ()); INSERT into orders (Orders.product, Orders.price, orders.createtime) VALUES ( "electric Car", (), now ()); INSERT into orders (Orders.product, Orders.price, orders.createtime) VALUES ("Phone" , and Now ()); INSERT into orders (Orders.product, Orders.price, orders.createtime) VALUES ("Ev ", " 2016-04-14 22:16:11"); INSERT into orders (Orders.product, Orders.price, orders.createtime) VALUES ("Phone" , "2016-04-14 22:16:11"); INSERT into orders (Orders.product, Orders.price, orders.createtime) VALUES (" Electric vehicles ",", "2016-04-14 22:16:11"); INSERT into orders (Orders.product, Orders.price, orders.createtime) VALUES ("Phone" , "2016-04-14 22:16:11");
If you have other ways to achieve the requirements of this article, welcome message.
Tips :
All SQL statements in this article are written according to the MySQL database.
Recommended :
SQL Basics Learning can go to W3school:
SQL Tutorial
Case and then else end learn to read the following blog post:
SQL case and then else end use method
SQL queries from query results