日期:2014-05-18  浏览次数:20498 次

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 sum
from 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 表@t 的别名
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 #try
select 89 union all
select 97  union all
select 83  union all
select 94  union all
select 83  union all
select 97  union all
select 99  union all
select 81  union all
select 84  union all
select 92  union all
select 98  union all
select 91  union all
select 82  union all
select 83  union all
select 95  union all
select 98  union all
select 81  

declare @id as int
declare @sum as int
set @id=0
set @sum=0
select @id=(case when @sum+bonus<1000 then id else @id end),
       @sum=@sum+(case when @sum+bonus<1000 then bonus else 0 end)
        from #try order by id
select 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

--各位都是牛叉人物