在连接具有一对多关系的两个表时,我想要一个结果,在一个表中显示多个表中具有null
值的所有值。
以下是一个例子:
tbl_Platform:PriKey = PlatformID
PlatformID PlatformDesc
1 Application
2 Cloud
3 Storage
4 Backup
tbl_Missed:PriKey = CustomerID + Week + PlatformID
CustomerID Week Missed Platform ID
49 1 2017-05-19 1
所需输出:
CustomerID Week Missed PlatformDesc
49 1 2017-05-19 Application
49 1 null Cloud
49 1 null Storage
49 1 null Backup
我最接近的是使用交叉连接,如下所示:
SELECT
dbo.tbl_Missed.CustomerID,
dbo.tbl_Missed.Week,
dbo.tbl_Missed.Missed,
dbo.tbl_Platform.PlatformDesc
FROM
dbo.tbl_Platform
CROSS JOIN dbo.tbl_MissedSPT
这给了我:
49 1 2017-05-19 Application
49 1 2017-05-19 Cloud
49 1 2017-05-19 Storage
49 1 2017-05-19 Backup
答案 0 :(得分:3)
如果missed
中存在匹配,则好像您想要获取属性platformID
的值,否则null
。尝试以下(希望没有拼写错误):
SELECT
dbo.tbl_Missed.CustomerID,
dbo.tbl_Missed.week,
CASE WHEN dbo.tbl_Missed.PlatformID = dbo.tbl_Platform.PlatformID
THEN dbo.tbl_Missed.missed
ELSE NULL
END as missed,
dbo.tbl_Platform.PlatformDesc
FROM dbo.tbl_Platform CROSS JOIN dbo.tbl_MissedSPT