表格
根据图像,表B是我的主表,而表A是表B的规则或条件。
我想写一个查询,这样当表a中的规则1代表具有指示符3的列[C1]时。然后在表B中查找具有相应值的相应列名,并替换FILL值。我想要的结果就像表C.
我该怎么做?
您只需要在两列上基于OR
条件进行联接
优选与MAX
聚合,以防存在多个匹配
SELECT
b.c1,
b.c2,
ISNULL(a.fill, b.fill) AS fill
FROM TableB b
OUTER APPLY (
SELECT MAX(fill) AS fill
FROM TableA a
WHERE a.[column] = 'c1' AND b.c1 = a.ind
OR a.[column] = 'c2' AND b.c2 = a.ind
) a;
您可以使用pivot
来实现这一点。将表A中的列名从行更改为列。
select B.c1,B.c2, (CASE WHEN A.ind IS NULL THEN 0 ELSE 1 END) AS fill
from tblB AS B
left outer join
(select *
from
(
select [column], ind, fill
from tblA
) src
pivot
(
max(fill)
for [column] in ([c1], [c2])
) piv
) AS A
ON (B.c1 = A.ind or B.c2 = A.ind)