繁体   English   中英

在SQL Server中合并行的问题

[英]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_idleg_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM