我有这个问题:
Select b.building_pk, bil.building_fk, bil.BillingAccountStatus_fk, b.ACTL_TNT_CT
From [DB].[Schema].Building b (nolock)
left Join [DB].[Schema].Billing bil (nolock) on bil.building_fk = b.building_pk
join ##GlobalTempTable1 tt (nolock) on tt.Building_fk = b.building_pk
Order by b.building_pk;
工作正常。但是我希望覆盖NULL
列和bil.building_fk
列中结果集中的bil.BillingAccountStatus_fk
,因为并非Billing tbl中的所有内容都存在于构建表中。
所以在下面写了下面的查询,但收到此错误消息。
Msg 102,Level 15,State 1,Line 7语法不正确' ='。
请协助。
SELECT b.building_pk, bil.building_fk As [BLD Key from Billing], bil.BillingAccountStatus_fk, b.ACTL_TNT_CT As [ActualTenantCount]
FROM [DB].[Schema].Building b (nolock)
join ##GlobalTempTable1 tt (nolock) ON tt.Building_fk = b.building_pk
left Join [DB].[Schema].Billing bil (nolock) ON
CASE
WHEN bil.building_fk IS NOT NULL
THEN bil.building_fk = b.building_pk AND bil.BillingAccountStatus_fk = bil.BillingAccountStatus_fk
WHEN bil.building_fk IS NULL
THEN bil.building_fk = NULL AND bil.BillingAccountStatus_fk = 'Not in Billing'
END
ORDER BY b.building_pk;
答案 0 :(得分:1)
很难说你想要做什么,因为这是非常错误的。不过,我认为您希望保持FROM
相同,并将CASE
语句放到SELECT中。
Select b.building_pk, CASE WHEN bil.Building_fk IS NULL THEN 'Not in Billing' ELSE bil.building_fk END as building_fk, bil.BillingAccountStatus_fk, b.ACTL_TNT_CT
From [DB].[Schema].Building b (nolock)
left Join [DB].[Schema].Billing bil (nolock) on bil.building_fk = b.building_pk
join ##GlobalTempTable1 tt (nolock) on tt.Building_fk = b.building_pk
Order by b.building_pk;
或者,更好的是,在这里使用COALESCE()
:
Select b.building_pk, COALESCE(bil.Building_fk,'Not in Billing') as building_fk, bil.BillingAccountStatus_fk, b.ACTL_TNT_CT
From [DB].[Schema].Building b (nolock)
left Join [DB].[Schema].Billing bil (nolock) on bil.building_fk = b.building_pk
join ##GlobalTempTable1 tt (nolock) on tt.Building_fk = b.building_pk
Order by b.building_pk;
答案 1 :(得分:0)
CASE
表达式不能用于设置您用于JOIN
的标准,它们可以在JOIN
条件的比较运算符的任意一侧使用,但是我认为您不需要,我认为您需要LEFT JOIN
中的COALESCE()
和SELECT
:
SELECT b.building_pk
, bil.building_fk As [BLD Key from Billing]
, COALESCE(bil.BillingAccountStatus_fk,'Not in Billing')
, b.ACTL_TNT_CT As [ActualTenantCount]
FROM [DB].[Schema].Building b
join ##GlobalTempTable1 tt
ON tt.Building_fk = b.building_pk
left Join [DB].[Schema].Billing bil
ON bil.building_fk = b.building_pk
ORDER BY b.building_pk;
修改:注意BillingAccountStatus_fk
来自bil
双方,因此已从JOIN
条件中删除。
答案 2 :(得分:0)
我猜你正试图做这样的事情:
SELECT b.building_pk, bil.building_fk As [BLD Key from Billing], bil.BillingAccountStatus_fk, b.ACTL_TNT_CT As [ActualTenantCount]
FROM [DB].[Schema].Building b (nolock)
join ##GlobalTempTable1 tt (nolock) ON tt.Building_fk = b.building_pk
left Join [DB].[Schema].Billing bil (nolock) ON
(bil.building_fk IS NOT NULL AND
(bil.building_fk = b.building_pk AND bil.BillingAccountStatus_fk = bil.BillingAccountStatus_fk))
OR (bil.building_fk IS NULL AND
(bil.building_fk = NULL AND bil.BillingAccountStatus_fk = 'Not in Billing'))
ORDER BY b.building_pk;
我将被误导使用nolock
再过一天......