根据专栏获取相关记录

时间:2017-07-25 09:13:59

标签: sql tsql select

我有一个包含这些字段的表

   id     tagNo      FromLayout    ToLayout
  -----------------------------------------
   1      10000         +A1           +B1
   2      10002         +B1           +B3
   3      10004         +B1           +F10
   4      10005         +B2           +F20
   5      10008         +B3           +C63
   6      10009         +D3           +D63
   7      10010         +D63          +G23
   8      10010         +D63          +G3

我希望拥有所有记录+一个新列,显示当前reocrds的ToLayout等于其FromLayout的记录。我希望得到像这样的结果

   id     tagNo      FromLayout    ToLayout     sNode
  ---------------------------------------------------
   1      10000         +A1           +B1       10002,10004
   2      10002         +B1           +B3       10008
   3      10004         +B1           +F10
   4      10005         +B2           +F20
   5      10008         +B3           +C63
   6      10009         +D3           +D63       10010,10012
   7      10010         +D63          +G23   
   8      10012         +D63          +G3

为此目的选择代码是什么?

2 个答案:

答案 0 :(得分:1)

尝试此查询。我已经执行并检查了输出:

SELECT * FROM (
select *, STUFF((SELECT ', ' + CAST(tagno AS VARCHAR(100)) 
     FROM layout 
     WHERE fromlayout = l.tolayout
     FOR XML PATH(''), TYPE)
    .value('.','NVARCHAR(MAX)'),1,2,' ') sNode  from layout l 
    )  a
    where sNode is not null

答案 1 :(得分:0)

我的方法是将您的原始表格加入CTE,该CTE会为每个tagNo计算FromLayout的CSV列表。

WITH cte AS (
    SELECT FromLayout,
        STUFF((
            SELECT ',' + t2.tagNo
            FROM yourTable t2
            WHERE t1.FromLayout = t2.FromLayout
            FOR XML PATH('')), 1, 1, '') AS sNode
    FROM yourTable t1
)

SELECT
    t1.*,
    COALESCE(t2.sNode, '') AS sNode
FROM yourTable t1
LEFT JOIN cte t2
    ON t1.ToLayout = t2.FromLayout