您的位置:程序门 -> ms-sql server -> 应用实例



请问查询“最新数据”的sql语句写法


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


请问查询“最新数据”的sql语句写法
发表于:2007-03-26 17:14:18 楼主
请问查询“最新数据”的sql语句写法
一表有以下数据(各城市的气温):
city   date     c
武汉   1         30
上海   1         32
南京   1         31
北京   1         29
上海   2         29
南京   2         38
北京   2         31
南京   3         30
北京   3         31

现在我需要查询各个城市的最近一次(最新的)气温信息,即查询结果是:
武汉   1         30
上海   2         29
南京   3         30
北京   3         31
发表于:2007-03-26 17:16:001楼 得分:0
--方法一:
select   *   from   tablename   a   where   not   exists(select   city   from   tablename   where   city   =   a.city   and   [date]   >   a.[date])
发表于:2007-03-26 17:16:422楼 得分:0
--方法二:
select   *   from   tablename   a   where   [date]   =   (select   max([date])   from   tablename   where   city   =   a.city)
发表于:2007-03-26 17:18:063楼 得分:0
--方法三:
select   a.*  
from   tablename   a  
inner   join  
(select   city,   max([date])   as   [date]   from   tablename   group   by   city)   b
on   a.city   =   b.city   and   a.[date]   =   b.[date]
发表于:2007-03-26 17:19:144楼 得分:0
select   *   from   table   a   where   [date]   in   (select   max([date])   from   tablename   where   city   =   a.city)
发表于:2007-03-27 18:50:095楼 得分:0
declare   @t   table(city   char(4),date   tinyint,c   int)
insert   @t   select   '武汉 ',   1   ,       30
union   all   select   '上海 '   ,1     ,     32
union   all   select   '南京 '   ,1   ,       31
union   all   select   '北京 '   ,1   ,       29
union   all   select   '上海 '   ,2   ,       29
union   all   select   '南京 '   ,2   ,       38
union   all   select   '北京 '   ,2   ,       31
union   all   select   '南京 '   ,3   ,       30
union   all   select   '北京 '   ,3   ,       31


select   *   from   @t   as   a
where   not   exists(select   1   from   @t   as   b   where   a.city   =   b.city   and   a.date   <   b.date)
发表于:2007-03-27 19:04:556楼 得分:0
declare   @t   table(city   char(4),date   tinyint,c   int)
insert   @t   select   '武汉 ',   1   ,       30
union   all   select   '上海 '   ,1     ,     32
union   all   select   '南京 '   ,1   ,       31
union   all   select   '北京 '   ,1   ,       29
union   all   select   '上海 '   ,2   ,       29
union   all   select   '南京 '   ,2   ,       38
union   all   select   '北京 '   ,2   ,       31
union   all   select   '南京 '   ,3   ,       30
union   all   select   '北京 '   ,3   ,       31

select   *   from   @t   t  
where  
not   exists(select   1   from   @t   where   city=t.city   and   date> t.date)

或:

select   *   from   @t   t  
where  
(select   count(1)   from   @t   where   city=t.city   and   date> t.date)=0
发表于:2007-03-27 22:11:127楼 得分:0
select   a.*   from   @t   a     join   (select   city   ,   max(date)   date     from   @t   group   by   city)   b   on   a.city=b.city   and   a.date=b.date
发表于:2007-04-09 15:15:158楼 得分:0
收藏
发表于:2007-04-12 10:19:009楼 得分:0
帮ding!


快速检索

最新资讯
热门点击