MSSQL 求用户最近一次消费记录的三种写法

IF OBJECT_ID('TempDB.dbo.#tbl_User') IS NOT NULL
	Drop Table #tbl_User
GO
CREATE TABLE #tbl_User
(
	uid		int,
	name	Nvarchar(64)
)
GO
IF OBJECT_ID('TempDB.dbo.#tbl_Records') IS NOT NULL
	DROP TABLE #tbl_Records
GO
CREATE TABLE #tbl_Records
(
	id					int  identity(1,1),
	uid					int,
	consumptiontime		datetime
)
INSERT INTO #tbl_User(uid,name)values(1,N'Tom'),(2,N'Jerry')
INSERT INTO #tbl_Records(uid,consumptiontime)values(1,'2019-01-01'),(1,'2019-02-01'),(1,'2019-03-01'),(2,'2019-05-01'),(2,'2019-06-01')


--way 1
SELECT u.name,b.consumptiontime
FROM #tbl_User u
left join (select r.uid,
				  max(r.consumptiontime) as consumptiontime 
			From #tbl_Records r 
			group by uid
		  ) b
on u.uid=b.uid

--way 2
select u.name,r.consumptiontime
From #tbl_Records r 
inner join #tbl_User u on r.uid=u.uid
where not exists(select 1 From #tbl_Records where #tbl_Records.uid=r.uid and #tbl_Records.consumptiontime>r.consumptiontime)

--way 3
select u.name,(select MAX(consumptiontime) as consumptiontime from #tbl_Records r where r.uid=u.uid) as consumptiontime
From #tbl_User u

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值