[英]Issue with merging of rows in sql server
I have tried this below code 我已经尝试下面的代码
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**
after running the query the data in "issue" column is not in proper order. 运行查询后,“问题”列中的数据顺序不正确。 means for example for vehicle_id-333 表示例如vehicle_id-333 . 。
how make correct allignment for this. 如何对此进行正确的分配。
thanks. 谢谢。
Why are you referring to the log_table
twice? 为什么要两次引用log_table
?
Second, SQL tables represent unordered sets. 其次,SQL表表示无序集。 You need a separate column to specify the ordering. 您需要单独的一列来指定顺序。 Let me assume that you have a log_id
column in the leg_table
with this information: 让我假设你有一个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;
I removed the group by
, because you probably don't need that. 我删除了的group by
,因为您可能不需要。
please try below query. 请尝试下面的查询。 below we are introducing ORDER
over comment field. 下面我们在评论字段中介绍ORDER
。 demo sql fiddle link: http://sqlfiddle.com/#!6/981c34/1 演示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.