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

2道sql面试题.求解.(华为的)
发2道sql面试题.
SQL code

题一
表tset
字段valueA,valueB
     A       B
     B       C
     C       D
     D       E
问如何得到一个树形结构.
E D C B A

题二
表tset
字段Id, name,value
     1  name1     2  
     2  name1     4 
     3  name2     5 
     4  name2     6 
     5  name2    10 
     6  name3     8
问如何得到结果.
name1,6,name2,21,name3,8  



------解决方案--------------------
SQL code

--1、
--> 测试数据:[tset]
if object_id('[tset]') is not null drop table [tset]
create table [tset]([valueA] varchar(1),[valueB] varchar(1))
insert [tset]
select 'A','B' union all
select 'B','C' union all
select 'C','D' union all
select 'D','E'

;with cte as
(
  select valueA from [tset] where valueB='e'
  union all
  select b.valueA from cte a inner join  [tset] b on a.valueA=b.valueB
)
select t.* from cte as t left join [tset] b on t.valueA=b.valueA
/*
valueA
------
D
C
B
A
*/

------解决方案--------------------
SQL code
第一题看精华帖BOM

第二题

create table PP
(
 id int identity(1,1) primary key,
 name nvarchar(30),
 [value] int 
)
insert into PP select 'name1',2
insert into PP select 'name1',4
insert into PP select 'name2',5
insert into PP select 'name2',6
insert into PP select 'name2',10
insert into PP select 'name3',8

select name,sum([value]) [value] from PP group by name
select * into UU from
(
 select name,sum([value]) [value] from PP group by name
) p
select * from UU

create function dbo.Getstr()
returns nvarchar(1000)
as 
begin
  declare @sql nvarchar(1000)
  set @sql=''
  select @sql=@sql+name+','+cast([value] as varchar(10)) from UU
  return @sql
end

select dbo.Getstr()


----------------------------------------------------------------------------------------------------------------
name1,6name2,21name3,8

(1 行受影响)