我正在尝试选择一个位置,然后选择旁边的报告行。
我的查询是:
SELECT (SELECT pos.PositionId
FROM PositionData pos
WHERE pos.PositionId = 1234) as [Topmost],
(SELECT pos.PositionId
FROM PositionData pos
WHERE pos.pdOpsReportLine = 1234) as [Reportline]
我得到的错误是:
Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
现在我知道这个错误意味着什么。
但我不想使用TOP语句,因为我想要在第二列中返回的行。
注意:以下语句应该是sql server中的列。
我想要的是:
Topmost Reportline
1234 2345
3456
4567
5678
我不想要的是:
Topmost
1234
2345
3456
4567
5678
最顶层的是首选的员工,如首席执行官和报告行是向他汇报的人。
答案 0 :(得分:3)
如果您希望以这种格式获取所有数据,可以执行以下操作:
select
case
when row_number() over(partition by pos.PositionId order by pos1.pdOpsReportLine) = 1 then
pos.PositionId
else
null
end as [Topmost],
pos1.PositionId as [Reportline]
from PositionData as pos
left outer join PositionData pos1 on pos.PositionId = pos1.pdOpsReportLine
where pos.pdOpsReportLine is null
order by pos.PositionId, pos1.pdOpsReportLine
请参阅sqlfiddle示例
答案 1 :(得分:0)
试试这个:
Declare @Topmost int=1234,
@MinPositionId int
SELECT @MinPositionId=min(pos.PositionId)
FROM PositionData pos
WHERE pos.pdOpsReportLine = @Topmost
select @Topmost Topmost,@MinPositionId Reportline
Union all
SELECT '',pos.PositionId
FROM PositionData pos
WHERE pos.pdOpsReportLine = @Topmost
and pos.PositionId != @MinPositionId