将组放在SQL中的同一行

时间:2013-07-30 09:18:22

标签: sql sql-server-2008

我已经构建了一个返回正确数据的报告,但我想知道是否可以在同一行而不是多行上进行分组。

一个例子会有所帮助!

报告目前正在输出

User       Count    FinishingNextMonth    Finishing3Months    Finishing6Months
Jo Bloggs  5        Person A     
Jo Bloggs  5                              Person B
Jo Bloggs  5                                                  Person C
Jo Bloggs  5                                                  Person D

但我宁愿输出

User       Count    FinishingNextMonth    Finishing3Months    Finishing6Months
Jo Bloggs  5        Person A              Person B            Person C
Jo Bloggs  5                                                  Person D

这是可能的,如果是这样的话?

代码如下:

declare @startdate datetime
declare @startdateplusone datetime
declare @startdateplusthree datetime
declare @startdateplussix datetime

set @startdate = '30 jul 2013'
set @startdateplusone = DATEADD(mm,1,@startdate)
set @startdateplusthree = DATEADD(mm,3,@startdate)
set @startdateplussix = DATEADD(mm,6,@startdate)

select 
u.username + ' ' + u.surname as Consultant, 
dbo.GET_CONTRACT_RUNNERS(u.UserId,@startdate) as Runners, 
(select fileas from objects where p.ApplicantId = ObjectID and p.EndDate > @startdate and p.EndDate <= @startdateplusone) as FinishingOneMonth,
(select fileas from objects where p.ApplicantId = ObjectID and p.EndDate > @startdateplusone and p.EndDate <= @startdateplusthree) as FinishingThreeMonths,
(select fileas from objects where p.ApplicantId = ObjectID and p.EndDate > @startdateplusthree and p.enddate <= @startdateplussix) as FinishingSixMonths
from placements p
inner join PlacementConsultants pc on pc.PlacementId = p.PlacementID
inner join Users u on u.UserId = pc.UserId
where p.StartDate < @startdate and p.EndDate > @startdate

group by u.UserName, u.Surname, EndDate, ApplicantId, u.userid
order by u.UserName, u.surname

0 个答案:

没有答案