------解决方案-------------------- select top 1 user,总和 from(select user,sum(account) as 总和 from tb_account group by user) where 总和>500 order by 总和 desc
------解决方案-------------------- 按你说的006是第一个
任何小于500都不满足,
所以就是查第一个大于500的咯?
------解决方案-------------------- 500哪里来的
------解决方案-------------------- select user sum(account) from 表 group by user having sum(account)>500
------解决方案-------------------- select top 1 * from T where [user] = (select [user] from T group by [user] having SUM(account)>500)
------解决方案--------------------
------解决方案-------------------- select top 1 user from 表 where accout>500
------解决方案-------------------- - -!围观学习
------解决方案--------------------
SQL code
DECLARE @TB TABLE([USER] NVARCHAR(10),ACCOUNT DECIMAL(18,2))
INSERT INTO @TB
SELECT '001',100.00 UNION ALL
SELECT '002',34.00 UNION ALL
SELECT '003',89.00 UNION ALL
SELECT '005',130.00 UNION ALL
SELECT '006',634.00 UNION ALL
SELECT '007',689.00
SELECT *,RCOUNT=(SELECT SUM(ACCOUNT) FROM @TB WHERE [USER]<=T.[USER]) FROM @TB T
/*
USER ACCOUNT RCOUNT
001 100.00 100.00
002 34.00 134.00
003 89.00 223.00
005 130.00 353.00
006 634.00 987.00
007 689.00 1676.00
*/
--取大于500的第一条即可
SELECT TOP 1 * FROM (SELECT *,RCOUNT=(SELECT SUM(ACCOUNT) FROM @TB WHERE [USER]<=T.[USER]) FROM @TB T) B WHERE RCOUNT>500
/*
USER ACCOUNT RCOUNT
006 634.00 987.00
*/
------解决方案--------------------
------解决方案--------------------
------解决方案-------------------- SELECT top 1 t2.[user] FROM [tb_account] as t1 , [tb_account] as t2 where t1.[user]<=t2.[User] group by t2.[User] having sum(t1.[account]) >500
------解决方案-------------------- 找出满足条件 account 【总和大于等于500】(sum(account) >= 500 )的第一个user。
你这个描述,应该就是寻找某个user的销售额超过500的结果集的第一条记录
难道不是吗
------解决方案-------------------- select ROW_NUMBER() OVER (ORDER BY userASC)AS ROWID,user,account into #temp from tb_account a
select user from #temp a where (select sum(account ) from #temp where ROWID<a.ROWID)<500 and (select COsum(account ) from #temp where ROWID<a.ROWID+1)>500
------解决方案--------------------