首页 新闻 会员 周边

关于两表连查的问题,请各位留步赐教

0
悬赏园豆:5 [已解决问题] 解决于 2010-08-24 09:15

从品牌表A中查出品牌名称Name,从产品表B中查出产品的品牌名称等于A.Name的数据的行数B.C,然后按照B.C对A表数据降序排列。

我想到的代码如下,但是这样不行,在第一个括号内"a.brandName”处报错了

 

select a.brandName,b.c from T_brand a,(select count(*) c from t_product where productname=a.brandname) b order by b.c desc
go

 

 

今日的主页 今日 | 初学一级 | 园豆:10
提问于:2010-08-23 17:24
< >
分享
最佳答案
0



IF NOT OBJECT_ID('[t_Brand]') IS NULL
DROP TABLE [t_Brand]
GO
CREATE TABLE [t_Brand]
(
[ID] int identity(1,1) primary key not null,
[brandName] Nvarchar(20) null
)
go
IF NOT OBJECT_ID('[t_Product]') IS NULL
DROP TABLE [t_Product]
GO
CREATE TABLE [t_Product]
(
[ID] int identity(1,1) primary key not null,
[ProductName] Nvarchar(20) null
)
go



INSERT [t_Brand]
SELECT '喜来登珠宝 ' union all
SELECT '香菲草 ' union all
SELECT '夏普' union all
SELECT '仙蒂罗娜' union all
SELECT '小鸡卡迪' union all
SELECT '小龙哈彼'
go

insert into [t_Product]
SELECT '喜来登珠宝 ' union all
SELECT '香菲草 ' union all
SELECT '夏普' union all
SELECT '仙蒂罗娜' union all
SELECT '小鸡卡迪' union all
SELECT '小龙哈彼' union all
SELECT '香菲草 ' union all
SELECT '夏普' union all
SELECT '仙蒂罗娜' union all
SELECT '小鸡卡迪' union all
SELECT '小龙哈彼' union all
SELECT '小龙哈彼' union all
SELECT '香菲草 ' union all
SELECT '仙蒂罗娜' union all
SELECT '小鸡卡迪' union all
SELECT '小龙哈彼' union all
SELECT '香菲草 ' union all
SELECT '夏普' union all
SELECT '夏普'
go



select a.brandName as 品牌数,
(
select count(1) from t_product t where t. productname=a.brandname) 产品数
from T_brand a
order by 产品数 desc
go

/*
品牌数 产品数
香菲草 4
夏普 4
小龙哈彼 4
仙蒂罗娜 3
小鸡卡迪 3
喜来登珠宝 1
*/

 


收获园豆:5
邀月 | 高人七级 |园豆:25475 | 2010-08-23 19:33
多谢二位关注,幸得二位提示,这个问题已解决。诚谢、、
今日 | 园豆:10 (初学一级) | 2010-08-24 09:15
其他回答(1)
0

select * from (select brandName,
(select COUNT(*) from  t_product where productname=T_brand.brandname) c from T_brand ) as a order by c desc

 

试试这个

skyzhou | 园豆:288 (菜鸟二级) | 2010-08-23 17:58
很遗憾这个不行,需求是这样的,现在要查询品牌但是在展示品牌的时候要根据该品牌所存在的商品数量降序展示出来。 你在上面给出方法查出来是这样的: brandname c 喜来宝珠宝 0 喜来登珠宝 0 夏普 0 夏普 0 仙帝罗娜 0 仙蒂罗娜 0 仙蒂罗娜 0 仙蒂罗娜 0 香菲草 0 香菲草 0 小鸡卡迪 0 小鸡卡迪 0 小鸡卡迪 0 小鸡卡迪 0 小龙哈彼 0 小龙哈彼 0 小龙哈彼 0 小龙哈彼 0 小龙哈彼 0 小龙哈彼 0 小龙哈彼 0 小龙哈彼 0
支持(0) 反对(0) 今日 | 园豆:10 (初学一级) | 2010-08-23 18:27
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册