查询表中某一列的每个值,第一次出现的所有记录
数据表结构:
用户名 登录时间 ……
用户a 1点 ……
用户a 10点 ……
用户b 3点 ……
用户b 7点 ……
用户c 0点 ……
用户c 3点 ……
…… ……
想得到的结果是:
用户a 1点 ……
用户b 3点 ……
用户c 0点 ……
请问这时sql改怎么写?谢谢!
------最佳解决方案--------------------select a.*
from tablename as a inner join (select 用户名,MIN(登录时间) as 登录时间 from tablename group by 用户名) as b
on a.用户名=b.用户名 and a.登录时间=b.登录时间
------其他解决方案--------------------
--方法一05新增:
select id,code,listdate
from (select rid=row_number()over (partition by convert(varchar(10),listdate) order by listdate desc),* from #t1)as t
where rid<=1
--方法二:使用cross apply
select distinct b.*
from #t1 as a
cross apply
(select top(1) * from #t1 where convert(varchar(10),a.listdate)=convert(varchar(10),listdate) order by listdate desc) as b
------其他解决方案--------------------declare @tt table(name varchar(10),[time] varchar(20))
insert @tt
select '用户a','1点' union all
select '用户a','10点' union all
select '用户b','3点' union all
select '用户b','7点' union all
select '用户c','0点' union all
select '用户c','3点'
select * from @tt as t where exists(select * from @tt where t.[time]<[time] and t.name = name)
select t.* from @tt as t cross apply(select * from @tt where t.[time]<[time] and t.name = name ) as p
select p.* from @tt as t cross apply(select * from @tt where t.[time]>[time] and t.name = name ) as p
------其他解决方案--------------------就是想求出所有用户当天首次登录的记录。
------其他解决方案----------------------> 测试数据:[TB]
if object_id('[TB]') is not null drop table [TB]
create table [TB]([用户名] varchar(5),[登录时间] varchar(4))
insert [TB]
select '用户a','1点' union all
select '用户a','10点' union all
select '用户b','3点' union all
select '用户b','7点' union all
select '用户c','0点' union all
select '用户c','3点'
select * from [TB] t WHERE NOT EXISTS(
SELECT 1 FROM Tb WHERE t.[用户名]=[用户名] and t.[登录时间]<[登录时间]
)
DROP TABLE TB
------其他解决方案--------------------将desc改成asc
--方法一05新增:
select id,code,listdate
from (select rid=row_number()over (partition by convert(varchar(10),listdate) order by listdate asc),* from #t1)as t