查询表中某一列的每个值,第一次出现的所有记录
数据表结构:
用户名 登录时间 ……
用户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
--方法一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
where rid<=2
--方法二:使用cross apply
select distinct b.*
from #t1 as a
cross apply
(select top(2) * from #t1 where convert(varchar(10),a.listdate)=convert(varchar(10),listdate) order by listdate asc) as b
SELECT 用户名,min(left(登录时间,len(登录时间)-1))+'点' as 登录时间 from tb
GROUP BY 用户名
if OBJECT_ID('test') is not null
drop table test
go
create table test(name varchar(20),login_time varchar(10))
insert into test
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 name,MIN(newtime)+'点' from(
select name,LEFT(login_time,charindex('点',login_time)-1) as newtime from test
) as b group by name
SELECT A.用户名,A.[登录时间] FROM (
SELECT t.用户名,t.[登录时间], ROW_NUMBER() OVER (Partition by t.用户名 ORDER BY len(t.[登录时间]),t.[登录时间])as Tid
FROM TB t)AS A
WHERE A.Tid=1