[英]Issue with merging of rows in sql server
我已經嘗試下面的代碼
select STUFF((
select ',' + t1 Issue
from Log_table t1
where t1.VID= t.VID
for xml path(''), type
).value('.', 'nvarchar(max)'), 1, 2, '') Cmnts,
Main_table .vehical_id, name, location,
from Log_table t RIGHT JOIN
main_table
on VID = vehicle_id
group by t.VID, Vehicle_id, name, location**
運行查詢后,“問題”列中的數據順序不正確。 表示例如vehicle_id-333 。
如何對此進行正確的分配。
謝謝。
為什么要兩次引用log_table
?
其次,SQL表表示無序集。 您需要單獨的一列來指定順序。 讓我假設你有一個log_id
列leg_table
有這樣的信息:
select STUFF((select ',' + t.Issue
from Log_table t
where t.VID = m.VID
order by t.log_id -- Assumes you have an id or some column for ordering
for xml path(''), type
).value('.', 'nvarchar(max)'), 1, 2, ''
) Cmnts, m.vehicle_id, m.name, m.location,
from main_table m;
我刪除了的group by
,因為您可能不需要。
請嘗試下面的查詢。 下面我們在評論字段中介紹ORDER
。 演示SQL小提琴鏈接: http ://sqlfiddle.com/#!6/981c34/1
select
m.vehicle_id,
m.name,
m.location,
STUFF(
(
select ',' + t.issue from
(
select *,
row_number() over (partition by vid order by issue asc) as r
from Log_table
) t
where t.VID= m.vehicle_id
order by t.r
for xml path(''), type
).value('.', 'nvarchar(max)'), 1, 2, '')
Cmnts
from
main_table m
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.