Where Case语句麻烦

Where Case Statement trouble

我有一个 sql 服务器 2008 table,比方说 "alpha",有三列。它们是 [ID]、[col1] 和 [col2]。

id|col1|col2
1 |X   |john1X|
1 |Y   |john1Y|
1 |Z   |john1Z|
2 |X   |john2|
3 |Y   |john3|
4 |X   |john4|

每个 ID 可能有多个条目。如果 col1 包含 'X',我希望显示该行。如果在 col1 中没有带有 'X' 的 ID,我想选择 'Y'。否则该行根本不应该出现。

对于上述示例数据,预期输出如下。

id|col1|col2
1 |X   |john1X|
2 |X   |john2|
3 |Y   |john3|
4 |X   |john4|

我一直在努力让这段代码起作用,

select * from alpha
where col1 = case
             when exists(select * from alpha where col1 = 'X') then 'X'
             else 'Y'
             end

然而,无论我如何重写代码,我都会得到以下输出。

id|col1|col2
1 |X   |john1X
2 |X   |john2 
4 |X   |john4

你可以用 row_number():

select a.*
from (select a.*,
             row_number() over (partition by id
                                order by col1
                               ) as seqnum
      from alpha
      where col1 in ('X', 'Y')
     ) a
where seqnum = 1;

注意:此特定逻辑按规定工作,因为 'X' < 'Y'。您可以使用 case 语句进行更一般的排序或更多值。

您的子查询中缺少一个子句...行

 when exists(select * from alpha where col1 = 'X') then 'X'

应该是

when exists(select * from alpha b where col1 = 'X' and b.id = alpha.id ) then 'X'

请注意,我在您的子查询中为 table 添加了一个别名,以便您可以将子查询的 table 的 ID 字段与主 table.[=12 进行匹配=]