首页 新闻 会员 周边

SQL 2005 查询的问题!

0
悬赏园豆:5 [已解决问题] 解决于 2013-02-19 09:28

取每一个用户 最后一天的数据。表中 :用户ID(UserId),更新日期(UpdateDate),更新动作(Action)

表中数据:用户的最后更新日期  是不一定相同。这三列数据都需要查出来。

一直 没有想通怎么写。求高手指点!

紫炁星的主页 紫炁星 | 初学一级 | 园豆:57
提问于:2013-02-18 10:33
< >
分享
最佳答案
0

select * from 表 left join (select UserId,max(UpdateDate) as UpdateDate from 表 group by userid) a on 表.userid=a.userid and 表.updatedate=a.updatedate

收获园豆:4
Rich.T | 老鸟四级 |园豆:3440 | 2013-02-18 17:50

漂亮 离我想要的答案 甚是接近。稍微修改下就可以用了。

select * from 表 right join (select UserId,convert(VARCHAR(10),max(UpdateDate),120) as UpdateDate from 表 group by userid) a on 表.userid=a.userid and convert(VARCHAR(10),max(表.UpdateDate),120)=a.updatedate

紫炁星 | 园豆:57 (初学一级) | 2013-02-19 09:27
其他回答(3)
0

我有一个有方法

感觉有点笨你可以看一下

我用我自己表试了一下没有问题

declare @id int
--建一个临时表
if object_id('Tempdb..#temp') is not null
begin
    drop table #temp
end 
else 
begin
    create table #temp
    (
        [用户ID] int ,
        [更新日期] varchar(100),
        [更新动作] varchar(200)
    )
end

declare cursor1 cursor for --用游标
select distinct UserId from [你的表]
open cursor1
fetch next from cursor1 into @id

while @@fetch_status=0
begin
    insert into #temp
    select top 1 UserId,UpdateDate,Action from [你的表] where UserId = @id
        order by UpdateDate desc
    fetch next from cursor1 into @id
end
close cursor1
deallocate cursor1

select * from  #temp
drop table #temp
收获园豆:1
li-peng | 园豆:954 (小虾三级) | 2013-02-18 11:05

方法可以实现。现在就是不知道 有没有更好点的方法。

支持(0) 反对(0) 紫炁星 | 园豆:57 (初学一级) | 2013-02-18 11:11

@紫炁星: 

如果有更好的说一声,我也学习一下

支持(0) 反对(0) li-peng | 园豆:954 (小虾三级) | 2013-02-18 11:12
0

有一个更笨的方法,先把更新日期按照降序排列,使用select语句选出top 1就行了!

Elaine00 | 园豆:294 (菜鸟二级) | 2013-02-18 14:04

查询的是用户最后一天 (一组数据)的数据 并不是第一条数据。

支持(0) 反对(0) 紫炁星 | 园豆:57 (初学一级) | 2013-02-18 15:47

@紫炁星: 哈哈~谢谢提醒哦!我看题太粗心了~

支持(0) 反对(0) Elaine00 | 园豆:294 (菜鸟二级) | 2013-02-18 15:48
0

max不就可以了。

清海扬波 | 园豆:825 (小虾三级) | 2013-02-18 17:25
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册