当我尝试以下代码时,我收到错误信息:
SELECT COUNT(*) FROM [ServerName].[dbo].[TableName1] B
WHERE right(B.TableName1, 2) = '34' AND
B.UnitId=
(select distinct D.UnitId
from [ServerName].[dbo].[TableName2] D
INNER JOIN @temp E ON D.UnitId=E.UnitId)
有谁知道如何解决它?它说子查询返回的值超过1。创建临时表并包含我想要计算的个人数量,由unitId。
答案 0 :(得分:1)
尝试使用连接而不是子查询:
SELECT COUNT(*)
FROM [ServerName].[dbo].[TableName1] B
INNER JOIN [ServerName].[dbo].[TableName2] D ON B.UnitId = D.UnitId
INNER JOIN @temp E ON D.UnitId = E.UnitId
WHERE RIGHT(B.TableName1, 2) = '34'
答案 1 :(得分:0)
子查询(select distinct
)返回了多个值。因此,B.UnitId
不能等于多个值。
如果IN
的确定具有多个值,则可以使用B.UnitId
。
SELECT COUNT(*)
FROM [ServerName].[dbo].[TableName1] B
WHERE right(B.TableName1, 2) = '34'
AND B.UnitId in (select D.UnitId
from [ServerName].[dbo].[TableName2] D
INNER JOIN @temp E ON D.UnitId=E.UnitId)
使用Distinct
时 IN
变得多余。