一行或另一行,但不能两者都有



如何选择一行或另一行,但不能同时选择这两行。

表格示例:

组件

  • ID:int(PK(
  • 姓名:nvarchar(120(
  • 损坏:钻头
  • BaseComponentId:int(FK(

描述

我想从组件表中选择所有组件,但如果有未损坏的组件,我希望它被选中,否则应该选择损坏的组件。然而,它们永远不能同时被损坏和未损坏。当然,分组是在BaseComponentId上完成的。

我希望你能帮助我。

您可以使用row_number():

select c.*
from (select c.*,
row_number() over (partition by BaseComponentId order by convert(int, damaged) asc) as seqnum
from components c
) c
where seqnum = 1;

这会为每个基本组件返回一行,并优先选择未损坏的组件。

您也可以使用相关的子查询:

select c.*
from components c
where c.id = (select top (1) c2.id
from components c2
where c2.BaseComponentId = c.BaseComponentId
order by c2.damaged asc
);

相关内容

最新更新