在数据库中有这样一张表格,其中主要包含三个字段,GoodsId(货物编号),TypeId(类型编号),State(状态)。货物编号不重复,GoodsId与TypeId之间属于N对1的关系,State为状态主要分为两种“null”和“1”,“null”表示该货物未卖出UnSold,“1”表示货物Sold。现在有如下业务,统计出类型编号下有多少货物Sold,多少货物UnSold。
数据库中的表格数据如下:
最后需要统计出(输出)的结果为:
问题分析:在上述问题中无疑所要用到的重点就是表格自身关联,以及计数方法count函数,以及分组group by等。在此根据题目提出的问题,我们需要用到的表格连接方法为内连接(inner join)。因为在表中存在至少一个匹配时,INNER JOIN 关键字返回行。
问题解决:根据所描述的问题,以及对于问题的分析,设计了如下sql。
1 select g1.TypeId,count(*)AS Sold,g3.UnSold from Goods g1 2 inner join 3 (select TypeId,count(*)AS UnSold from Goods g2 WHERE State='null' 4 group by g2.TypeId) g3 5 on g1.TypeId = g3.TypeId 6 WHERE State ='1' group by g1.TypeId,g3.UnSold
附件:为了让大家更好的去实践,博主特将建表语句以及插入语句贴出。以供大家学习。
-- 建表语句
CREATE TABLE Goods(
GoodsId VARCHAR(255),
TypeId VARCHAR(255),
State VARCHAR(255)
);
--- 插入语句
insert into Goods(GoodsId,TypeId,State) values('001','1','1');
insert into Goods(GoodsId,TypeId,State) values('002','1','null')
insert into Goods(GoodsId,TypeId,State) values('003','1','null');
insert into Goods(GoodsId,TypeId,State) values('004','1','null');
insert into Goods(GoodsId,TypeId,State) values('005','1','null');
insert into Goods(GoodsId,TypeId,State) values('006','1','1');
insert into Goods(GoodsId,TypeId,State) values('001','2','1');
insert into Goods(GoodsId,TypeId,State) values('002','2','null');
insert into Goods(GoodsId,TypeId,State) values('003','2','null');
insert into Goods(GoodsId,TypeId,State) values('004','2','1');
insert into Goods(GoodsId,TypeId,State) values('005','2','null');
insert into Goods(GoodsId,TypeId,State) values('006','2','null');
insert into Goods(GoodsId,TypeId,State) values('007','2','1');
insert into Goods(GoodsId,TypeId,State) values('008','2','null');
insert into Goods(GoodsId,TypeId,State) values('001','3','1');
insert into Goods(GoodsId,TypeId,State) values('002','3','null');
insert into Goods(GoodsId,TypeId,State) values('003','3','null');
转自:http://www.cnblogs.com/DonaHero/p/6059466.html