Select Distinct top 100 Uid,ProDate,ProTime,min(Auto_No) As Auto_No
from Has_Swipedata
where format(Prodate, 'dd/MM/yyyy') = Format(Getdate(), 'dd/MM/yyyy') and
Is_Active='N' and
Uid not like '%[^0-9]%' and Uid != ''
Group by Uid, ProDate, ProTime
来自上方查询的表数据: Uid ProDate ProTime Auto_No
4057 2017-06-14 16:51:12.0000000 1584
4057 2017-06-14 16:51:13.0000000 1585
4057 2017-06-14 16:51:15.0000000 1586
预期结果:
Uid ProDate ProTime Auto_No
4057 2017-06-14 16:51:12.0000000 1584
答案 0 :(得分:1)
您无需将日期格式化为字符串即可比较日期。如果ProDate
已经是date
数据类型,请与convert(date,getdate())
进行比较。
这会得到每个Auto_No
和Uid
的第一个/分钟ProDate
,以及ProTime
的{{1}}。
使用Auto_No
:
cross apply()
或使用内部联接:
select distinct top 100
sd.Uid
, sd.ProDate
, x.ProTime
, x.Auto_No as Auto_No
from Has_Swipedata sd
cross apply (
select top 1 *
from Has_Swipedata i
where i.Uid = sd.UID
and i.ProDate = sd.ProDate
order by i.Auto_No asc
) x
where sd.ProDate = convert(date,getdate())
and sd.Is_Active = 'N'
and sd.Uid not like '%[^0-9]%'
and sd.Uid != ''
答案 1 :(得分:0)
看看想要的结果,我猜是
Select top(1) with ties Uid, ProDate, ProTime, Auto_No
from Has_Swipedata
where format(Prodate, 'dd/MM/yyyy') = Format(Getdate(), 'dd/MM/yyyy') and
Is_Active='N' and
Uid not like '%[^0-9]%' and Uid != ''
order by row_number() over(partition by Uid,ProDate order by Auto_No)
演示
select top(1) with ties Uid, ProDate, ProTime, Auto_No
from
(values
(4057, '2017-06-14', '16:51:12.0000000', 1584),
(4057, '2017-06-14', '16:51:13.0000000', 1585),
(4057, '2017-06-14', '16:51:15.0000000', 1586),
(4058, '2017-06-14', '16:51:12.0000000', 1587),
(4058, '2017-06-14', '16:51:13.0000000', 1588),
(4058, '2017-06-14', '16:51:15.0000000', 1589)
) Has_Swipedata (Uid,ProDate,ProTime, Auto_No)
order by row_number() over(partition by Uid,ProDate order by Auto_No)
返回
Uid ProDate ProTime Auto_No
1 4057 2017-06-14 16:51:12.0000000 1584
2 4058 2017-06-14 16:51:12.0000000 1587
如果您只需要前100个Uid + ProDate,请使用Select top(100)包装查询......
select top(100) *
from (
select top(1) with ties Uid, ProDate, ProTime, Auto_No
from
(values
(4057, '2017-06-14', '16:51:12.0000000', 1584),
(4057, '2017-06-14', '16:51:13.0000000', 1585),
(4057, '2017-06-14', '16:51:15.0000000', 1586),
(4058, '2017-06-14', '16:51:12.0000000', 1587),
(4058, '2017-06-14', '16:51:13.0000000', 1588),
(4058, '2017-06-14', '16:51:15.0000000', 1589)
) Has_Swipedata (Uid,ProDate,ProTime, Auto_No)
order by row_number() over(partition by Uid,ProDate order by Auto_No)
) result
答案 2 :(得分:0)
也许在ProTime中应用相同的Auto_No规则会生成预期结果:
Select top 100
Uid, ProDate, min(ProTime) as ProTime, min(Auto_No) As Auto_No
from Has_Swipedata
where Prodate = convert(date, GETDATE()) and
Is_Active='N' and
Uid not like '%[^0-9]%' and Uid != ''
Group by Uid, ProDate
或提供更多具有预期结果的数据样本。