SQL中GROUP BY的问题,请高手指点。
现在有三个表,结构如下:
create table gq_type1 --一级分类
(
id int identity(1,1) primary key,
type1_name nvarchar(20) not null --一级分类名称
)
go
create table gq_type2 --二级分类
(
id int identity(1,1) primary key,
type1_id int foreign key references gq_type1(id),
type2_name nvarchar(20) not null,
)
go
create table product_gq_info --信息表(本表的其它字段省略)
(
id int identity(1,1), --产品编号
type1_id int foreign key references gq_type1(id) on delete cascade, --大类别编号,必填
type2_id int foreign key references gq_type2(id) on delete cascade, --小类别编号,必填
type3_id int foreign key references gq_type3(id) on delete cascade, --三级分类
gq_type int default 0, --类型
youxiaoqi varchar(10), --本信息有效期
jointime smalldatetime default getdate() --发布时间
)
go
要实现的效果是这样的:
第一行:列出信息表中,各个大类有多少个
SQL语句:select gq_type1.id,type1_name,count(product_gq_info.type1_id) as pnum from product_gq_info right join gq_type1 on product_gq_info.type1_id=gq_type1.id group by all gq_type1.id,type1_name
id type1_name pnum
----------- -------------------- -----------
1 鲜切花类 20
2 盆栽植物类 1
3 绿化苗木类 1
4 盆景奇石类 0
5 园林资材 0
6 园林景观类 0
效果就是我要的效果
第二行,显示信息表下某个指定的大类下的各个小类,并得出各小类的信息有多少个。下面是当前gq_type2表中的数据,注意:这里面type1_id=3的有两个。
id type1_id type2_name
----------- ----------- --------------------
1 1 hu
2 2 观叶植物
3 5 园林机具
4 6 绿化施工
5 4 树桩盆景
6 3 常绿乔木
7 3 常绿灌木
GROUP GY SQL语句:select gq_type2.id,type2_name,count(product_gq_info.type2_id) as pnum2 from product_gq_info right join gq_type2 on product_gq_info.type2_id=gq_type2.id where product_gq_info.type1_id=3 and gq_type=1 and dateadd(day,cast(youxiaoqi as int),product_gq_info.jointime)>getdate() group by product_gq_info.type2_id,gq_type2.id,type2_name
运行结果:
id type2_name type1_id pnum2
----------- -------------------- ----------- -----------
1 hu 1 0
2 观叶植物 2 0
3 园林机具 5 0
4 绿化施工 6 0
5 树桩盆景 4 0
6 常绿乔木 3 1
7 常绿灌木 3 0
去掉group by all中的那个all运行结果:
id type2_name type1_id pnum2
----------- -------------------- ----------- -----------
6 常绿乔木 3 1
很明显,这里有一个type1_id=3的那个类没有显示出来
请问下,如何写才能让它只显示某个指定大类的小类名称,如果该类下面那个小类没有内容也要显示出来该小类名称。但是又不显示其它大类下的小类呢?