请教一个SQL语句

King_hhuang 2009-02-12 03:51:52
我有一个表tableA,我需要查出每台终端(终端号字段:termNum)最近的一条刷卡记录(刷卡时间字段:readTime),查出的结果我希望类似下面这种形式:

终端号 记录时间 卡号 ……
1 2009-02-12 11:31:00 100001 ……
2 2009-02-12 11:33:01 100002 ……
3 2009-02-12 11:32:02 100007 ……
4 2009-02-12 11:30:02 100013 ……

……

好像要用到group by,但是怎么写呢,请大家指点一下
...全文
84 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
肥龙上天 2009-02-12
  • 打赏
  • 举报
回复

补充一个,屡试不爽


select * from (
select * ,rn = row_number() over (partition by 终端号 order by 记录时间 desc)from tb
)t where rn = 1

funsuzhou 2009-02-12
  • 打赏
  • 举报
回复
有谁可以说明一下原理吗?
King_hhuang 2009-02-12
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 libin_ftsafe 的回复:]
SQL code
select t.* from tableA t where not exists(select 1 from tableA where 终端号=t.终端号 and 记录时间>t.记录时间)

select t.* from tableA t where t.记录时间=(select top 1 记录时间 from tableA where 终端号=t.终端号 order by 记录时间 desc)

select t.* from tableA t where t.记录时间=(select max(记录时间) from tableA where 终端号=t.终端号)

select a.* from tableA a,(select 终端号,max(记录…
[/Quote]

大佬果然是大佬,佩服佩服!!
lgxyz 2009-02-12
  • 打赏
  • 举报
回复
select t.* from tableA t where not exists(select 1 from tableA where 终端号=t.终端号 and 记录时间>t.记录时间) 
那就这样,这样比较直接
取出所有列
htl258_Tony 2009-02-12
  • 打赏
  • 举报
回复

select termNum 终端号,max(readTime) 记录时间,CardNo 卡号
from tableA
group by termNum ,CardNo
King_hhuang 2009-02-12
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 libin_ftsafe 的回复:]
SQL code
select t.* from tableA t where not exists(select 1 from tableA where 终端号=t.终端号 and 记录时间>t.记录时间)

select t.* from tableA t where t.记录时间=(select top 1 记录时间 from tableA where 终端号=t.终端号 order by 记录时间 desc)

select t.* from tableA t where t.记录时间=(select max(记录时间) from tableA where 终端号=t.终端号)

select a.* from tableA a,(select 终端号,max(记录…
[/Quote]

高手,这几种都可以吗?
King_hhuang 2009-02-12
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 lgxyz 的回复:]
SQL codeSELECT 卡号,最近刷卡时间=MAX(记录时间) FROM TB GROUP BY 卡号
[/Quote]

这个显示的结果只有两列,我要所有数据都显示的
子陌红尘 2009-02-12
  • 打赏
  • 举报
回复

select t.* from tableA t where not exists(select 1 from tableA where 终端号=t.终端号 and 记录时间>t.记录时间)

select t.* from tableA t where t.记录时间=(select top 1 记录时间 from tableA where 终端号=t.终端号 order by 记录时间 desc)

select t.* from tableA t where t.记录时间=(select max(记录时间) from tableA where 终端号=t.终端号)

select a.* from tableA a,(select 终端号,max(记录时间) as 记录时间 from tableA group by 终端号) b where a.终端号=b.终端号 and a.记录时间=b.记录时间
mschen 2009-02-12
  • 打赏
  • 举报
回复
select * from 表 a
where 记录时间 = (select max(记录时间) from 表 where 终端号=a.终端号)
lgxyz 2009-02-12
  • 打赏
  • 举报
回复
SELECT 卡号,最近刷卡时间=MAX(记录时间) FROM TB GROUP BY 卡号
子陌红尘 2009-02-12
  • 打赏
  • 举报
回复
select t.* from tableA t where not exists(select 1 from tableA where 终端号=t.终端号 and 记录时间>t.记录时间)

34,587

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧