SQL 從查詢結果裡查詢

2021-07-11 05:45:10 字數 2329 閱讀 8293

有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
這個結果確實滿足了我的需求,但是存在乙個問題,就是當天數多了的時候,會看得我頭暈眼花的。如果查詢結果是下面這個樣子,我想看起來會舒服得多:

when origintable.product = "電動車"

then origintable.total else

0end) "電動車",

sum(case

when origintable.product = "手機"

then origintable.total else

0end) "手機"

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

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基礎知識學習可以去w3school:

sql 教程

case when then else end 學習可以看下面這篇博文:

sql case when then else end 用法

SQL 查詢結果為 XML

原始資料 1.auto模式 selectorderno,createdate,username,address fromwhir order orderinfo forxmlauto,xmlschema 結果 2.raw模式selectorderno,createdate,username,addr...

SQL 查詢結果為 XML

原始資料 1.auto模式 selectorderno,createdate,username,address fromwhir order orderinfo forxmlauto,xmlschema 結果 2.raw模式selectorderno,createdate,username,addr...

mysql php結果排序 SQL查詢結果排序

公升序排序 使用order by子句時,預設情況下資料是按公升序排列的,故可以用asc關鍵字指點公升序排列,或者不指定,預設就是公升序,顯示效果是一樣的,如下圖 降序排序 當需要查詢結果降序排列時,必須在排序後指定desc關鍵字。如下圖是檢視職員薪水的降序排 公升序排序 使用order by子句時,...