2015-06-17 251 views
0

我有一個表有三個列的每個唯一值相結合的行基於日期時間

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行基於日期時間上升的結果,每一個TICKET_ID結合起來,一行應該是這樣的

TICKET_ID ASSIGN 
5692 ASSIGN-5  
5740 ASSIGN-5  
5741 ASSIGN-5  
5742 ASSIGN-4 ASSIGN-5 

我該如何建立結果?

回答

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 

閱讀本article亞倫貝特朗的更多細節。

0

這裏是需要的結果設置..給出了兩個解決方案第一種是簡單地連接兩個表票號的基礎上,第二屆加盟分配的基礎上,排它會給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

感謝