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

这个统计语句如何写?多谢

2012-01-20 
这个统计语句怎么写?谢谢select*fromt1wheret_idin(2,3)得到以下结果:idt_idn_id227326422052196218736838

这个统计语句怎么写?谢谢
select   *   from   t1   where   t_id   in   (2,3)
得到以下结果:

id             t_id           n_id
2                 2                   7
3                 2                   6
4                 2                   20
5                 2                   19
6                 2                   18
7                 3                     6
8                 3                     8
10               3                   21
11               3                   20

我想得到的结果是:
n_id   counts
7             1
6             2
20           2
19           1
18           1
8             1
21           1

并且选出的结果需要让counts字段降序排列  
t2表的id和t1表的n_id是对应的   需要将t2表中对应id的name显示出来
也就是
name   counts
a1             1
a2             2
a3             2
a4             1
a5             1
a6             1
a7             1

这样的语句怎么写?可以分开写   我在存储过程里面做   谢谢


[解决办法]

create table t1(id int,t_id int,n_id int)
insert t1 select 2,2,7
union all select 3,2,6
union all select 4,2,20
union all select 5,2,19
union all select 6,2,18
union all select 7,3,6
union all select 8,3,8
union all select 10,3,21
union all select 11,3,20
go

create table t2(id int,name varchar(10))
insert t2 select 7, 'a1 '
union all select 8, 'a2 '
union all select 18, 'a3 '
union all select 19, 'a4 '
union all select 21, 'a5 '
union all select 20, 'a6 '
union all select 6, 'a7 '

go

select distinct b.[name] , counts=(select count(n_id) from t1 where n_id=a.n_id)
from t1 a , t2 b
where a.n_id=b.id
order by counts

----------结果---------
name counts
1a1
1a2
1a3
1a4
1a5
2a6
2a7


这个不是你要的结果么?

热点排行