根据日期时间为每个唯一值组合行

时间:2015-06-17 03:19:05

标签: sql-server sql-server-2008-r2

我有一个包含三列的表

TICKET_ID   ASSIGN  ASSIGN_DATE
5692    ASSIGN-5    2013-07-17 19:37:09.000
5740    ASSIGN-5    2013-07-17 19:37:09.000
5741    ASSIGN-5    2013-07-17 19:37:09.000
5742    ASSIGN-5    2013-07-17 10:40:15.000
5742    ASSIGN-4    2013-07-17 19:37:09.000

我需要根据日期时间升序结果将每个ASSIGN的{​​{1}}行合并为一行

TICKET_ID

我该如何建立结果?

2 个答案:

答案 0 :(得分:2)

您可以使用FOR XML PATH('')

WITH SampleData(TICKET_ID, ASSIGN, ASSIGN_DATE) AS(
    SELECT 5692, 'ASSIGN-5', CAST('2013-07-17 19:37:09.000' AS DATETIME) UNION ALL
    SELECT 5740, 'ASSIGN-5', '2013-07-17 19:37:09.000' UNION ALL
    SELECT 5741, 'ASSIGN-5', '2013-07-17 19:37:09.000' UNION ALL
    SELECT 5742, 'ASSIGN-5', '2013-07-17 10:40:15.000' UNION ALL
    SELECT 5742, 'ASSIGN-4', '2013-07-17 19:37:09.000'
)
SELECT
    TICKET_ID,
    ASSIGN = STUFF((
        SELECT ' ' + ASSIGN
        FROM SampleData
        WHERE TICKET_ID = sd.TICKET_ID
        ORDER BY ASSIGN_DATE ASC
        FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'
    ), 1, 1, '')
FROM SampleData sd
GROUP BY sd.TICKET_ID

阅读Aaron Bertrand的article了解更多详情。

答案 1 :(得分:0)

这里是必需的结果集..给出两个解决方案首先是简单地在票证id的基础上加入两个表,第二个连接在Assign行的基础上它将给出13行

----------1st-------------------

Select T.*,A.* from Tikets T with(nolock)
join
Assignement A with(nolock)
on a.TICKET_ID = t.TICKET_ID
order by t.ASSIGN_DATE

-----------2nd-----------------

Select T.*,A.* from Tikets T with(nolock)
join
Assignement A with(nolock)
on a.ASSIGN like t.ASSIGN +'%' 
order by t.ASSIGN_DATE

enter link description here

由于