测试用例:
表一:
ID NAME QQ PHONE
------------------------------------------
1 秦云 10102800 13500000
2 在路上 10378 13600000
3 LEO 10000 13900000
表二:
ID NAME 上机时间 管理员
------------------------------------------
1 秦云 2004-01-01 李大伟
2 秦云 2005-01-01 马化腾
3 在路上 2005-01-01 马化腾
4 秦云 2005-01-01 李大伟
5 在路上 2005-01-01 李大伟
6 陈扬 2006-01-01 李彦宏
目的:从表1中取所有人员列表,从表2中取上机次数和管理员.
获取管理员拼接串
CREATE
FUNCTION
GetNameStr(
@name
NVARCHAR
(
200
))
RETURNS NVARCHAR ( 200 )
AS
BEGIN
DECLARE @temp NVARCHAR ( 200 )
, @reValue NVARCHAR ( 200 )
DECLARE myCur CURSOR FOR
(
SELECT 管理员 from LogInfo
WHERE NAME = N ' 秦云 '
)
OPEN myCur
FETCH NEXT FROM myCur INTO @temp
WHILE @@FETCH_STATUS = 0
BEGIN
SET @reValue = ISNULL ( @reValue + N ' , ' , '' ) + @temp
FETCH NEXT FROM myCur INTO @temp
END
CLOSE myCur
DEALLOCATE myCur
RETURN @reValue
END
RETURNS NVARCHAR ( 200 )
AS
BEGIN
DECLARE @temp NVARCHAR ( 200 )
, @reValue NVARCHAR ( 200 )
DECLARE myCur CURSOR FOR
(
SELECT 管理员 from LogInfo
WHERE NAME = N ' 秦云 '
)
OPEN myCur
FETCH NEXT FROM myCur INTO @temp
WHILE @@FETCH_STATUS = 0
BEGIN
SET @reValue = ISNULL ( @reValue + N ' , ' , '' ) + @temp
FETCH NEXT FROM myCur INTO @temp
END
CLOSE myCur
DEALLOCATE myCur
RETURN @reValue
END
主查询:
SELECT
NAME,
COUNT
(ID) 上机次数,dbo.GetNameStr(NAME)
FROM LogInfo T2
WHERE EXISTS
(
SELECT 1
FROM StuInfo T1
WHERE T1.NAME = T2.NAME
)
GROUP BY NAME
FROM LogInfo T2
WHERE EXISTS
(
SELECT 1
FROM StuInfo T1
WHERE T1.NAME = T2.NAME
)
GROUP BY NAME
结果:
NAME 上机次数 (无列名)
------------------------------------
秦云 3 李大伟,马化腾,李大伟
在路上 2 李大伟,马化腾,李大伟