我试图编写一个查询,通过他们的abbreiviations而不是他们的代码对组织进行分组。但是,在某些情况下,orgcode字段将为空白。这意味着我需要查看客户邮政编码字段并根据该字段进行相应分组。我写了以下查询:
SELECT
dem.N1_1_NUMBER,
dem.N1_8_POSTCODE,
src.N1_3_ORG_CODE_SEEN,
Case
When src.N1_3_ORG_CODE_SEEN IN ('XRT01', 'XRT02') Then 'ILR'
When src.N1_3_ORG_CODE_SEEN IN ('XRTBP', 'XRTBU') Then 'HGF'
When src.N1_3_ORG_CODE_SEEN = 'XRTBW' Then 'HGW'
When src.N1_3_ORG_CODE_SEEN IS NULL
Then (Select
Case
When LEFT(dem.N1_8_POSTCODE, 4) in ('LA1 ', 'LA2 ', 'LA3 ', 'LA4 ', 'LA5 ', 'LA6 ','LA7 ','LA8 ') Then 'RLI'
When LEFT(dem.N1_8_POSTCODE, 4) in ('LA9 ', 'LA10', 'LA11') Then 'WGH'
When LEFT(dem.N1_8_POSTCODE, 4) in ('LA12', 'LA13', 'LA14', 'LA15', 'LA16') Then 'FGH'
Else 'Unknown'
End
From Register.dbo.tblMAIN_REFERRALS mr
LEFT JOIN Register.dbo.tblDEMOGRAPHICS dem
ON mr.Customer_ID = dem.Customer_ID
) End as [ORG SEEN]
FROM Register.dbo.MAIN_REFERRALS src
Left JOIN Register.dbo.DEMOGRAPHICS dem
ON src.PATIENTID = dem.PATIENTID
当我运行查询时,出现以下错误:
子查询返回的值超过1。这是不允许的 子查询跟随=,!=,<,< =,>,> =或当子查询用作 表达。
我不完全确定查询为什么不起作用,所以任何帮助都会受到赞赏。
答案 0 :(得分:0)
我认为你不需要那个子查询..尝试这样的事情
SELECT dem.N1_1_NUMBER,
dem.N1_8_POSTCODE,
src.N1_3_ORG_CODE_SEEN,
CASE
WHEN src.N1_3_ORG_CODE_SEEN IN ( 'XRT01', 'XRT02' ) THEN 'ILR'
WHEN src.N1_3_ORG_CODE_SEEN IN ( 'XRTBP', 'XRTBU' ) THEN 'HGF'
WHEN src.N1_3_ORG_CODE_SEEN = 'XRTBW' THEN 'HGW'
WHEN src.N1_3_ORG_CODE_SEEN IS NULL THEN
CASE
WHEN LEFT(dem.N1_8_POSTCODE, 4) IN ( 'LA1 ', 'LA2 ', 'LA3 ', 'LA4 ',
'LA5 ', 'LA6 ', 'LA7 ', 'LA8 ' ) THEN 'RLI'
WHEN LEFT(dem.N1_8_POSTCODE, 4) IN ( 'LA9 ', 'LA10', 'LA11' ) THEN 'WGH'
WHEN LEFT(dem.N1_8_POSTCODE, 4) IN ( 'LA12', 'LA13', 'LA14', 'LA15', 'LA16' ) THEN 'FGH'
ELSE 'Unknown'
END
END AS [ORG SEEN]
FROM Register.dbo.MAIN_REFERRALS src
LEFT JOIN Register.dbo.DEMOGRAPHICS dem
ON src.PATIENTID = dem.PATIENTID
答案 1 :(得分:0)
这意味着你的子查询拉动邮政编码字段会返回多行......子查询不会引用外部查询中的任何内容,因此它会返回所有内容。 除非我错过了什么......而不是做
From Register.dbo.tblMAIN_REFERRALS mr
LEFT JOIN Register.dbo.tblDEMOGRAPHICS dem
ON mr.Customer_ID = dem.Customer_ID
尝试
From Register.dbo.tblMAIN_REFERRALS mr
WHERE mr.Customer_ID = dem.Customer_ID
这样做会使子查询仅返回与外部查询的每一行相关的结果。