我有像这样的数据
TagNo FromBay FromPanel ToBay ToPanel FromDevice FromTerminal FromRef
1000 +A =D +E +F +X1 1 D1
1001 +A =D +E +F +X1 1 D2
1001 +A =D +E +F +X1 2 D3
1002 +A =D +E +F +X1 2 D4
1000 +A =D +E +F +X5 2 D5
我想要这个
TagNo FromBay FromPanel ToBay ToPanel FromDevice FromTerminal FromRef
1000,1001 +A =D +E +F +X1 1 D1,D2
1001,1002 +A =D +E +F +X1 2 D3,D4
这意味着如果FromBay FromPanel ToBay ToPanel FromDevice具有相同的值,则返回这些reocrds的连接TagNo和FromRef
我怎么能在TSQL中做到这一点
答案 0 :(得分:0)
您应该能够使用 XML PATH 获取输出,在SQLFiddle中创建了一个示例,没有使用您需要的所有列,但是你应该能够通过样本得到你想要的东西:
SELECT FromBay,FromTerminal,
FromRef = STUFF((SELECT ',' + FromRef FROM GroupTbl i
WHERE
i.FromBay = o.FromBay AND
i.FromTerminal = o.FromTerminal
FOR XML PATH('')),1,1,''),
TagNo = STUFF((SELECT ',' + TagNo FROM GroupTbl i
WHERE
i.FromBay = o.FromBay AND
i.FromTerminal = o.FromTerminal
FOR XML PATH('')),1,1,'')
FROM GroupTbl o
GROUP BY FromBay,FromTerminal
答案 1 :(得分:0)
如果连接仅用于行对,则可以执行此操作:
select t1.TagNo + ',' + t2.TagNo as TagNo,
t1.FromBay,t1.FromPanel,t1.ToBay,t1.ToPanel,t1.FromDevice,t1.FromTerminal,
t1.FromRef + ',' + t2.FromRef
from t t1
inner join t t2
on (t1.FromBay=t2.FromBay and t1.FromPanel=t2.FromPanel
and t1.ToBay=t2.ToBay and t1.ToPanel=t2.ToPanel
and t1.FromDevice=t2.FromDevice and t1.FromTerminal=t2.FromTerminal
and t1.TagNo<t2.TagNo)