如何查询每天的第一条记录?

youzhj 2010-03-18 10:14:34
表tb,中有字段dt(datetime),f1(int),每天有很多数据,现在要查询某月每天的第一条记录,该如何写SQL语句?
...全文
239 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
milkman_nuaa 2010-03-19
  • 打赏
  • 举报
回复
declare @t as datetime
set @t=getdate() -- datetime input

select top 1 * from #tb
where datediff(mm, @t, dt) = 0
order by dt
youzhj 2010-03-18
  • 打赏
  • 举报
回复
人都走了啊?俺在等会看看
youzhj 2010-03-18
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 happyflystone 的回复:]
SQL code
select *
from tb b
where not exists(select 1 from tb where datediff(d,b.dt,dt) = 0 and dt < b.dt)
[/Quote]我把你这个句子改了一下
select a.Rdt,a.kc_ep,a.Kid from KC_EP a,tb_order b
where not exists(select 1 from KC_EP where datediff(dd,a.Rdt,Rdt)=0 and Rdt<a.Rdt)
order by a.Rdt,b.Sid

可是运行起来太慢了,是不是 因为我用了联合查询或者表中数据过大的原因啊?有没有办法可以优化一下?
语句中表tb_order是另外做的一个排序表,以便按照某字段的特定顺序来排序查询。
东那个升 2010-03-18
  • 打赏
  • 举报
回复
select * from (
select *,ROW_NUMBER() over(partition by convert(char(10),dt,120) order by dt ) as rn
from tb ) a
where rn=1
-狙击手- 2010-03-18
  • 打赏
  • 举报
回复
select *
from tb b
where not exists(select 1 from tb where datediff(d,b.dt,dt) = 0 and dt < b.dt)
-狙击手- 2010-03-18
  • 打赏
  • 举报
回复
不好意思 ,打错了

呵呵,b
youzhj 2010-03-18
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 happyflystone 的回复:]
select *
from tb b
where not exists(select 1 from tb where datediff(d,b.dt,dt) = 0 and dt> a.dt)
[/Quote]
是a.dt还是b.dt啊?运行不正确啊
-狙击手- 2010-03-18
  • 打赏
  • 举报
回复
select *
from tb b
where not exists(select 1 from tb where datediff(d,b.dt,dt) = 0 and dt> a.dt)
--小F-- 2010-03-18
  • 打赏
  • 举报
回复
select
*
from
tb t
where
f1=(select max(f1) from tb where dt=t.dt)
and
month(dt)='xx'

34,587

社区成员

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

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