0

我在存储过程中组合表时遇到问题。
注意:字段“时间”是 varchar
第一个表 (tbTime)

Time
08:00:00
08:30:00
09:00:00
09:30:00
10:00:00
10:30:00
11:00:00
11:30:00
12:00:00

第二个表(tbClientData)
从 tbclientdata 中选择时间,名称,其中约会='2013/10/26' 按时间排序

Time        Name
08:30:00    MaLa
08:35:00    Mara
08:40:00    Sarah
09:00:00    Nafira
09:00:00    Sarah AmeLia
09:00:00    Denur Jumaran
10:00:00    MuLyono
10:00:00    Lucky Strada Nova

我想要这样的条件时间表的结果

Time        Name
08:00:00    -
08:30:00    MaLa, Mara, Sarah
09:00:00    Nafira, Sarah AmeLia, Denur Jumaran
09:30:00    -
10:00:00    MuLyono, Lucky Strada Nova
10:30:00    -
11:00:00    -
11:30:00    -
12:00:00    -

感谢阅读或回答^_^

GBU

我试过这个

select c1.Time, 
stuff((select distinct ', '+cast(Name as varchar(200))
from tbclientdata c2 where c2.time=c1.time
for xml path('')),1,1,'')
from tbclientdata c1
where c1.Appointment='2013/10/26'
group by c1.Time

结果是……

Time         Name
08:30:00     MaLa
08:35:00     Mara, Mr
08:40:00     Sarah
09:00:00     Denur Jumaran, Nafira, Sarah AmeLia, Yason
10:00:00     Lucky Strada Nova, MuLyono
4

2 回答 2

1
WITH HalfHours AS (
    SELECT CONVERT(datetime, Time, 108) As HalfHour
    FROM tbTime
)
,HalfHourNames AS (
    SELECT DATEADD(second, -SecondsSinceHalfHour, RealTime) As HalfHour
          ,Name
    FROM tbclientdata
         CROSS APPLY (
             SELECT CONVERT(datetime, Time, 108) As RealTime
         ) AS CA1
         CROSS APPLY (
             SELECT (DATEPART(minute, RealTime) % 30) * 60 + DATEPART(second, RealTime) As SecondsSinceHalfHour
         ) AS CA2
    WHERE Appointment = '20131026'
)
SELECT HalfHours.HalfHour
      ,COALESCE(CA2.CommaSeparatedNames, '-') AS Names
FROM HalfHours
     CROSS APPLY (
         SELECT (SELECT ', ' + HalfHourNames.Name
                 FROM HalfHourNames
                 WHERE HalfHours.HalfHour = HalfHourNames.HalfHour
                 FOR XML PATH('')
                ) AS RawCommaSeparatedNames
     ) AS CA1
     CROSS APPLY (
         SELECT STUFF(CA1.RawCommaSeparatedNames, 1, 2, '') AS CommaSeparatedNames
     ) AS CA2
GROUP BY HalfHours.HalfHour
        ,CA2.CommaSeparatedNames
于 2013-10-28T15:30:09.790 回答
0

尝试这个:

;WITH HalfHourIntervals AS
(
    SELECT CAST('2013-10-26 00:00:00' AS DATETIME) interval
    UNION ALL
    SELECT DATEADD(MINUTE, 30, interval)
    FROM HalfHourIntervals
    WHERE interval < '2013-01-01 23:59:59'
)    

select hi.Interval, stuff(
    (select distinct ', '+cast(Name as varchar(200))
     from tbclientdata c2 where c2.time=c1.time
     for xml path('')),1,1,'')
from tbclientdata c1
right join HalfHourIntervals hi on hi.interval = cast(round(cast(cast(convert(varchar(30),c1.[Time],121) as datetime) as float) * (24.0/0.5),0)/(24.0/0.5) as datetime)
where c1.Appointment='2013-10-26'
group by c1.[Time]
于 2013-10-28T15:35:51.450 回答