createtable test
( 產品 char(10),顏色 char(5),數量 int
);insertinto test
values ('產品1','紅色',123),('產品1','藍色', 126),('產品2','藍色',103),('產品2','紅色',NULL),('產品2','紅色',89),('產品1','紅色',203),('產品3','紅色',23),('產品3','藍色',203);/*按產品分類,僅列出各類商品中紅色多于藍色的商品名稱及差額數量*/select 產品, sum(if (顏色='紅色',數量,0))- sum(if (顏色='藍色',數量,0)) as 差額
from test
groupby 產品
havingsum(if (顏色='紅色',數量,0))> sum(if (顏色='藍色',數量,0));/*按產品分類,將數據按下列方式進行統計顯示:產品,紅色,藍色*/select 產品, sum(if (顏色='紅色',數量,0)) as 紅色總和,sum(if (顏色='藍色',數量,0)) as 藍色總和
from test
groupby 產品;/*以上問題復雜做法:*/select x.cno,(x.數量-y.數量) as 差額
from (select cno,col,sum(num) as 數量from a groupby cno,col) x,(select cno,col,sum(num) as 數量from a groupby cno,col) y
where x.cno=y.cno and x.col='紅色'and y.col='藍色'and x.數量>y.數量
groupby x.cno;/*第二題*/selectdistinct(cno),(selectsum(num) from a x where x.cno=a.cno and col='紅色'groupby cno,col) as 紅色,(selectsum(num) from a x where x.cno=a.cno and col='藍色'groupby cno,col) as 藍色
from a;