1

我有以下表格:

T1

  ID  PRIORITY
  1      1
  2      1
  3      2
  4      4

T2

ID  SERVICE
1   PSTN
1   ADSL
3   ADSL

T3

ID   DEVICE
1    BSC1
3    BSC7 
4    BSC7

我想作为输出

ID  PRIORITY SERVICE/DEVICE
1      1        PSTN
1      1        ADSL
1      1        BSC1
2      1
3      2        ADSL
3      2        BSC7

如何使用 UNION ALL 绑定这些表?我还必须为 T1 放置 WHERE 子句 WHERE PRIORITY!=4

一个 id 的输出表中的总数应该是 T2+T3 的摘要(对于 ID=1 2+1=3),但对于 ID=2,它也应该存在于表输出中,第二列为空白。

谢谢

4

2 回答 2

3

如果你可以只使用 aUNION而不是UNION ALL这应该给你你想要的

SELECT t1.Id, t1.Priority, COALESCE(t2.Service, '') AS [Service/Device]
FROM t1
LEFT JOIN t2 ON t1.Id = t2.Id
WHERE t1.Priority != 4

UNION 

SELECT t1.Id, t1.Priority, COALESCE(t3.Device, '') AS [Service/Device]
FROM t1
LEFT JOIN t3 ON t1.Id = t3.Id
WHERE t1.Priority != 4

SQL 小提琴示例

于 2012-10-05T03:48:04.313 回答
1
select T1.id , T1.PRIORITY ,T2.SERVICE  as service/Device from  t1 
left outer join T2 on T2.id=T1.id where T1.PRIORITY!=4
union all
select T1.id , T1.PRIORITY ,T3.DEVICE as service/Device from  t1 
left outer join T3 on T3.id=T1.id where PRIORITY!=4
于 2012-10-05T04:21:11.747 回答