您的位置:程序门 -> ms-sql server -> 基础类



如何获取相同记录的第一条?


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


如何获取相同记录的第一条?
发表于:2007-05-26 11:39:50 楼主
有一表table
记录如下
id           goods     title     content
1             xq               ..         ..
2             xq
3             gy
4             gy


我想取得字段goods值为 'xq '和值为 'gy '的第一条,也就是获取goods= 'xq '的第一条,
获取goods= 'gy '的第一条记录

如何写sql语句?
谢谢?
发表于:2007-05-26 11:43:211楼 得分:0
select   top   1   *   from   table
where   goods   =   'xq '
发表于:2007-05-26 11:46:352楼 得分:0
用一条sql语句怎么实现?
发表于:2007-05-26 11:47:323楼 得分:0
显示出两条记录。
发表于:2007-05-26 11:48:484楼 得分:0
select   top   1   *   from   table
where   goods   in   ( 'xq ', 'gy ')

或者
select   top   1   *   from   table
where   goods   =   'xq '
union
select   top   1   *   from   table
where   goods   =   'gy '
发表于:2007-05-26 11:49:375楼 得分:0
select   top   1   *   from   table
where   goods   in   ( 'xq ', 'gy ')
这个错了
发表于:2007-05-26 11:50:176楼 得分:0
create   table   t(id   int,goods   varchar(10))
insert   t   select   1, 'xq '
union   all   select   2, 'xq '
union   all   select   3, 'gy '
union   all   select   4, 'gy '

select   id,goods   from   t   a   where   id   in

select   top   1   id   from   t   where   goods=a.goods
)

drop   table   t

id                     goods            
-----------   ----------  
1                       xq
3                       gy

(所影响的行数为   2   行)
发表于:2007-05-26 11:51:487楼 得分:0
学习
发表于:2007-05-26 11:55:528楼 得分:0
很简单的方法:
create   table   #t(id   int   identity(1,1)   ,   goods   nvarchar(20))
insert   into   #t
select   'xq '   union   all        
select   'xq '   union   all        
select   'gy '   union   all        
select   'gy '  

select   *   from   #t   as   a   where   not   exists(select   1   from   #t   as   b   where   b.goods=a.goods   and   b.id <a.id)
drop   table   #t
/*
id goods
------------------------
1 xq
3 gy
*/
发表于:2007-05-26 12:01:249楼 得分:0


select   *   from   t   a   where   exists   (select   1   from   t     where   a.goods=goods   and   a.id <id     )
发表于:2007-05-26 12:05:3710楼 得分:0
select   min(id)   id,goods
  from   table   group   by   goods   order   by   id
发表于:2007-05-26 12:15:1711楼 得分:0
select   *   from   table_pqs   where   not   exists(select   1   from   table_pqs   as   a  
where   table_pqs.goods=a.goods   and   table_pqs.id> a.id)
发表于:2007-05-26 12:18:0812楼 得分:0
select   top   1   *   from   table
where   goods   =   'xq '

select   top   1   *   from   table
where   goods   =   'gy '

和这条复合语句

select   id,goods   from   t   a   where   id   in

select   top   1   id   from   t   where   goods=a.goods
)


哪个节省资源,速度快呀?



快速检索

最新资讯
热门点击