SQL / TSQL根据子查询列中的所有值更新值

时间:2018-08-01 18:51:10

标签: sql-server tsql

我有下表:

TableA

Id    |material |Group
1      pipe      NULL
2      faucet    NULL
3      bracket   NULL
4      beam      NULL

TableB

TableAId |Program
1         1
1         2
2         3
3         1
3         4

我想根据材料所属的程序更新TableA上的 Group 列。组由程序确定,例如

  

group1 :1 || 2 || 1 && 2

     

第2组:3 || 4 || 3 && 4

     

公共组:存在但与上述程序组不匹配的任何组

     

否分组

所需结果表

Id    |material |Group
1      pipe      group1
2      faucet    group2
3      bracket   commonGroup
4      beam      noGroup

目前,我已经查询了所有材料及其程序(如果材料不存在)的表格(如果材料中没有程序,则在该列中放置NULL),但是我很难检查每个材料具有相同ID的行,以确定应该分配哪个组。

SELECT
    TableA.Id, TableB.Program 
FROM 
    TableA
FULL JOIN 
    TableB ON TableA.Id = TableB.TableAId

1 个答案:

答案 0 :(得分:0)

这很棘手。我建议在子查询中计算组,然后将这些信息重新加入select ( select productcode, productname from Mytable where category = 'membership' for xml path('Product'), root('Membership'), type) ,( select productcode, productname from Mytable where category = 'event' for xml path('Product'), root('Event'), type) for xml path('Products') 中:

update