当前位置: 代码迷 >> Sql Server >> MS SQL一道面试题解决方案
  详细解决方案

MS SQL一道面试题解决方案

热度:20   发布时间:2016-04-27 14:00:13.0
MS SQL一道面试题
近日面试看到一道面试题,没做出来,一直心存困惑,上来求个解。 
题目,按照id顺序,给每个人发放奖金,求奖金数累加小于1000时的id号 
如下表数据 
  id bonus 
1 89 
2 97 
3 83 
4 94 
5 83 
6 97 
7 99 
8 81 
9 84 
10 92 
11 98 
12 91 
13 82 
14 83 
15 95 
16 98 
17 81 
答案:select id from table_name a  
where (select sum(bonus) from table_name where id < a.id ) <1000  
and (select sum(bonus) from table_name where id < (a.id+1) ) > 1000
这里数据名后跟个a 和a.id 看不懂!求解释

------解决方案--------------------
table_name a 中的a是表别名
a.id 是指table_name中的id字段
------解决方案--------------------
= 楼下 太高深了
------解决方案--------------------
SQL code
with cte as(select id,bonus,(select sum(bonus) from table_name where id <= t.id) as sumfrom table_name t)select id from cte where sum < 1000
------解决方案--------------------
select ID from @t a where 1000>(select SUM(bonus) from @t where id<=a.id)

a [email protected] 的别名
a.id 表别名中"字段ID",id<=a.id 意思是子查询中的ID要<= “select ID from @t a”这个查询中的ID当前值。
------解决方案--------------------
SQL code
create table #try(id int identity(1,1), bonus int)insert #tryselect 89 union allselect 97  union allselect 83  union allselect 94  union allselect 83  union allselect 97  union allselect 99  union allselect 81  union allselect 84  union allselect 92  union allselect 98  union allselect 91  union allselect 82  union allselect 83  union allselect 95  union allselect 98  union allselect 81  declare @id as intdeclare @sum as intset @id=0set @sum=0select @id=(case when @sum+bonus<1000 then id else @id end),       @[email protected]+(case when @sum+bonus<1000 then bonus else 0 end)        from #try order by idselect id from #try where id<=11
------解决方案--------------------
探讨
引用:
SQL code

with cte as
(
select id,bonus,(select sum(bonus) from table_name where id <= t.id) as sum
from table_name t
)
select id from cte where sum < 1000
with ate as 看……

------解决方案--------------------
是公用表达式
探讨

引用:
SQL code

with cte as
(
select id,bonus,(select sum(bonus) from table_name where id <= t.id) as sum
from table_name t
)
select id from cte where sum < 1000
with ate as……

------解决方案--------------------
SQL code
--各位都是牛叉人物
  相关解决方案