查询将不同行中的数据合并为一个

时间:2014-01-06 12:06:04

标签: sql-server-2008

我在SQL Server 2008中有两个表:

MEETING:

MeetingID(bigint)  MeetingStartTime(datetime)  MeetingEndTime(datetime)


 100                 2014-01-05 17:10:13.000   2014-01-05 17:10:13.000

-----------------------------------------------------------------------

反馈:

    MeetingID(bigint)  QuestionID(int)  Response(varchar 210)

   100                         1               Very Good

   100                         2               Average

 -------------------------------------------------------------

我想要的结果是当前日期的12.00AM-11.59PM:

MeetingID  MeetingStartTime  MeetingEndTime  QuestionID Response QuestionID Response

100       2014-01-05 17:10  2014-01-05 17:10      1     Very Good    2      Average

我写了一个查询:

select m.MeetingID, m.MeetingStartTime, mMeetingEndTime, r.QuestionID, r.Response
from MEETING minner joinFEEDBACK ronm.MeetingID=r.MeetingID
where m.MeetingID<GETDATE() and m.MeetingID>DATEADD(hour,-12,GETDATE())

但我得到的结果是:

MeetingID MeetingStartTime    MeetingEndTime    QuestionID    Response

  100       2014-01-05 17:10   2014-01-05 17:10     1          Very Good

  100      2014-01-05 17:10    2014-01-05 17:10     2          Average

请帮助。

1 个答案:

答案 0 :(得分:0)

请根据您的要求使用以下代码:

如果您有多个响应ID,请在下面的脚本中添加这些列。

;with cte as
    (
    select  a.MeetingId,convert(date,a.MeetingStartTime) MeetingStartTime,
    convert(date,a.MeetingEndTime) MeetingEndTime,
    b.QestionID,b.Response
    from MEETING a
    join FEEDBACK b on a.MeetingId = b.MeetingId 
    where convert(date,a.MeetingStartTime) = convert(date,getdate()) and convert(date,a.MeetingEndTime) = convert(date,getdate())
    )

        select a.MeetingId,a.MeetingStartTime,a.MeetingEndTime,
        QuestionID = (select QestionID from FEEDBACK  b where a.MeetingId = b.MeetingId and b.QestionID = min(a.QestionID) ),
        Response =  (select Response from FEEDBACK  b where a.MeetingId = b.MeetingId  and b.QestionID = min(a.QestionID)  ),
        QuestionID = (select QestionID from FEEDBACK  b where a.MeetingId = b.MeetingId and b.QestionID = min(a.QestionID) + 1 ),
        Response =  (select Response from FEEDBACK  b where a.MeetingId = b.MeetingId  and b.QestionID = min(a.QestionID) +1 )
        from 
        cte a
        group by 
        a.MeetingId,a.MeetingStartTime,a.MeetingEndTime