两个表之间的 SQL 相同单元需要 1 个单元格中的订单号 [英] SQL same unit between two tables needs order numbers in 1 cell

查看:21
本文介绍了两个表之间的 SQL 相同单元需要 1 个单元格中的订单号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 张桌子:

SELECT UnitId FROM dbo.tblUnits

SELECT UnitId, WorkOrderNumber FROM dbo.tblWorkOrders

我需要显示 dbo.tblUnits 中的所有 UnitId,然后在 1 列中显示所有以逗号分隔的 WorkOrders.

I need to display all UnitId's from dbo.tblUnits then in 1 column diplay all the WorkOrders seperated by a comma.

这里是一些示例数据:dbo.tblUnits:

So here is some sample data: dbo.tblUnits:

UnitId
123
156
178

dbo.tblWorkOrders

dbo.tblWorkOrders

UnitId WorkOrderNumber
123        1
123        2
156        4
178        5
178        9
178        10

我必须使用 tblUnits 表,因为我要从中提取更多数据,但我想显示最终结果:

I have to use the tblUnits table because I am pulling more data from it but the final result I want to show this:

UnitId   WorkOrderNumber
123         1,2
156         4 
178         5,9,10

有什么想法吗?

谢谢

推荐答案

select 
    UnitId, 
    stuff((select ', ' + convert(varchar, WorkOrderNumber) 
           from tblWorkOrders t2 where t1.UnitId = t2.UnitId 
           for xml path('')),
          1,2,'') WorkOrderNumbers
from tblWorkOrders t1
group by UnitId

这篇关于两个表之间的 SQL 相同单元需要 1 个单元格中的订单号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆