這是網(wǎng)友的問題,我當(dāng)時立馬給出了自己的解決方案,但是沒有想到中間有點小問題,發(fā)現(xiàn)后經(jīng)過自己仔細(xì)調(diào)試,完全得到正確結(jié)果后,那個網(wǎng)友已經(jīng)結(jié)帖了。我的代碼遂成為雞肋,食之無味,棄之可惜。但是我覺得我的代碼確實還是挺經(jīng)典的,所以整理了一下,供各位網(wǎng)友欣賞。 
問題: 
  
假設(shè)環(huán)境如下:
表1: id, name, qq, phone,
表中數(shù)據(jù): 1 秦云 10102800 13500000
2 在路上 10378 13600000
3 leo 10000 13900000
表2: id, name, 上機(jī)時間,管理員,
表中數(shù)據(jù): 1 秦云 2004-1-1 李大偉
2 秦云 2005-1-1 馬化騰
3 在路上 2005-1-1 馬化騰
4 秦云 2005-1-1 李大偉
5 在路上 2005-1-1 李大偉
實現(xiàn)目的:從表1中取所有人員列表,從表2中取上機(jī)次數(shù)和管理員.
上機(jī)人員名單 上機(jī)次數(shù) 管理員(上這幾次機(jī)的每個管理員都列出來)
秦云 3 李大偉,馬化騰,李大偉
在路上 2 馬化騰,李大偉
leo 0
如果不算管理員那一列的話,我是這樣寫的。
select 表1.name as 姓名, count(表2.id) as 上機(jī)次數(shù)
from 表1 left outer join
表2 on 表1.name = 表2.name
group by 表1.名稱
解答: 
測試用例 
create table 表1( --drop table 表1
id int,
name varchar(10),
qq varchar(10),
phone varchar(20)
)
insert into 表1 values(1 ,’秦云’ ,’10102800’ ,’13500000’)
insert into 表1 values(2 ,’在路上’ ,’10378’ ,’13600000’)
insert into 表1 values(3 ,’leo’ ,’10000’ ,’13900000’)
create table 表2( --drop table 表2
id int,
name varchar(10) ,
上機(jī)時間 datetime,
管理員 varchar(10)
)
insert into 表2 values(1,’秦云’ ,cast(’2004-1-1’ as datetime),’李大偉’)
insert into 表2 values(2,’秦云’ ,cast(’2005-1-1’ as datetime),’馬化騰’)
insert into 表2 values (3,’在路上’ ,cast(’2005-1-1’ as datetime),’馬化騰’)
insert into 表2 values(4,’秦云’ ,cast(’2005-1-1’ as datetime),’李大偉’)
insert into 表2 values(5,’在路上’ ,cast(’2005-1-1’ as datetime),’李大偉’)
程序部分
create function getnamestr(@name nvarchar(10))
returns nvarchar(800)
as
begin
declare @namestr nvarchar(800)
declare @tempstr nvarchar(800)
declare @flag int
declare mycur cursor for ( select 管理員 from 表2 where 表2.name = @name )
open mycur
fetch next from mycur into @tempstr
set @flag = 0
while @@fetch_status = 0
begin
if @flag = 0
begin
set @namestr = @tempstr
end
else
begin
set @namestr = @namestr + ’,’ + @tempstr
end
set @flag = @flag + 1
fetch next from mycur into @tempstr
end
close mycur
deallocate mycur
return @namestr
end
select 表2.name as 姓名, count(id) as 上機(jī)次數(shù), dbo.getnamestr(表2.name) as 管理員
from 表2
where 表2.name in ( select 表1.name from 表1 )
group by 表2.name
測試結(jié)果:
姓名 上機(jī)次數(shù) 管理員
--------------------------------------------------------------
秦云 3 李大偉,馬化騰,李大偉
在路上 2 馬化騰,李大偉
 
新聞熱點
疑難解答
圖片精選