征求sql语句,最新一次购买时间

jncharles 2010-09-01 07:45:45
一个用table中有三个字段
yhbh:用户编号
gmsj:购买时间
ye:余额
如何查找最近一次购买时间的那行记录,并插入另一个表中
如:
yhbh gmsj ye
001 2010-09-09 0.90
001 2010-09-10 0.80
001 2010-09-11 0.70
001 2010-09-12 0.60
002 2010-09-09 0.90
002 2010-09-10 0.80
我只想查询
001 2010-09-12 0.60
002 2010-09-10 0.80
这才是我需要的,如何查找
...全文
208 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
hhiew 2010-09-02
  • 打赏
  • 举报
回复
select *
from
[tb] t
where
gmsj=(select max(gmsj) from [tb] where yhbh=t.yhbh )
lcqtgb 2010-09-01
  • 打赏
  • 举报
回复
select a.yhbh,a.gmsj,b.ye from( 
(select yhbh, max(gmsj)gmsj from tb
group by yhbh) a join (select yhbh ,gmsj, ye from tb) b

on a.yhbh=b.yhbh and a.gmsj=b.gmsj)
「已注销」 2010-09-01
  • 打赏
  • 举报
回复
if not object_id('tb') is null
drop table tb
Go
Create table tb([yhbh] nvarchar(3),[gmsj] Datetime,[ye] decimal(18,2))
Insert tb
select N'001','2010-09-09',0.90 union all
select N'001','2010-09-10',0.80 union all
select N'001','2010-09-11',0.70 union all
select N'001','2010-09-12',0.60 union all
select N'002','2010-09-09',0.90 union all
select N'002','2010-09-10',0.80
GO

SELECT M.*
FROM tb M
INNER JOIN (SELECT yhbh, MAX(gmsj)maxDate FROM TB GROUP BY yhbh) N
ON M.yhbh=N.yhbh AND M.gmsj=N.maxDate
ORDER BY M.yhbh

yhbh gmsj ye
---- ----------------------- ---------------------------------------
001 2010-09-12 00:00:00.000 0.60
002 2010-09-10 00:00:00.000 0.80

(2 row(s) affected)
jaydom 2010-09-01
  • 打赏
  • 举报
回复

select [yhbh], [gmsj],[ye]
from tb a
where exists (select 1 from tb
where a.yhbh=yhbh
group by yhbh
having MAX(gmsj)=a.gmsj)

yhbh gmsj ye
001 2010-09-12 00:00:00.000 0.60
002 2010-09-10 00:00:00.000 0.80
水族杰纶 2010-09-01
  • 打赏
  • 举报
回复
if not object_id('tb') is null
drop table tb
Go
Create table tb([yhbh] nvarchar(3),[gmsj] Datetime,[ye] decimal(18,2))
Insert tb
select N'001','2010-09-09',0.90 union all
select N'001','2010-09-10',0.80 union all
select N'001','2010-09-11',0.70 union all
select N'001','2010-09-12',0.60 union all
select N'002','2010-09-09',0.90 union all
select N'002','2010-09-10',0.80
Go
select *
from [tb] t
where [gmsj]=(select max([gmsj])
from tb
where [yhbh]=t.[yhbh])
yhbh gmsj ye
---- ----------------------- ---------------------------------------
002 2010-09-10 00:00:00.000 0.80
001 2010-09-12 00:00:00.000 0.60
水族杰纶 2010-09-01
  • 打赏
  • 举报
回复
select * 
from [table] t
where not exists(select 1
from [table]
where yhbh=t.yhbh and gmsj>t.gmsj)

27,582

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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