首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

关于多表查询的一个有关问题

2012-03-23 
关于多表查询的一个问题?表1编号日期代码1000012007-01-0100011000102007-01-1001001001012007-01-1500012

关于多表查询的一个问题?
表1
编号               日期                 代码  
100001       2007-01-01         0001  
100010       2007-01-10         0100  
100101       2007-01-15         0001  
200200       2007-01-15         0002  
200206       2007-01-15         0003  
3111111     2007-01-16         0101    
101010       2007-01-18         0006    
      -                   -                       -      
表2
类别           代码                 名称
水果           0001                 苹果
水果           0002                 苹果
水果           0100                 苹果
水果           0004                 苹果
水果           0003                 西瓜
水果           0008                 西瓜
文具           0101                 铝笔
文具           0106                 铝笔
现在想得到类别是 "水果 "的 "苹果 "、 "西瓜 "在表1中各有多少条记录?即根据所列数据得到:
名称         记录数
苹果             3
西瓜             1

这样的sql语句怎样写?


[解决办法]

select b.名称,count(*)
from 表1 a inner join 表2 b on a.代码=b.代码
where b.类别= '水果 '
group by b.代码,b.名称
[解决办法]
select a.名称,count(*) as 记录数 from table2 a join table 1 b on a.代码=b.代码 and a.名称 in ( '苹果 ', '西瓜 ')
group by a.名称

[解决办法]
create table A(编号 varchar(10), 日期 datetime, 代码 varchar(10))
insert A select '100001 ', '2007-01-01 ', '0001 '
union all select '100010 ', '2007-01-10 ', '0100 '
union all select '100101 ', '2007-01-15 ' , '0001 '
union all select '200200 ', '2007-01-15 ', '0002 '
union all select '200206 ', '2007-01-15 ', '0003 '
union all select '3111111 ', '2007-01-16 ', '0101 '
union all select '101010 ', '2007-01-18 ', '0006 '
go
create table B(类别 varchar(10), 代码 varchar(10), 名称 varchar(10))
insert B select '水果 ', '0001 ', '苹果 '
union all select '水果 ', '0002 ', '苹果 '
union all select '水果 ', '0100 ', '苹果 '
union all select '水果 ', '0004 ', '苹果 '


union all select '水果 ', '0003 ', '西瓜 '
union all select '水果 ', '0008 ', '西瓜 '

union all select '文具 ', '0101 ', '铝笔 '
union all select '文具 ', '0106 ', '铝笔 '


select B.名称, count(*) from A
inner join B on A.代码=B.代码 and B.类别= '水果 ' and B.名称 in( '西瓜 ', '苹果 ')
group by B.名称

--result
名称
---------- -----------
苹果 4
西瓜 1

(2 row(s) affected)

热点排行