SQL Server独占选择列值

uqdfh47h  于 2023-02-03  发布在  SQL Server
关注(0)|答案(3)|浏览(147)

假设我从select返回下表
| 病例ID|文档ID|文档类型Id|文件类型|失效日期|
| - ------|- ------|- ------|- ------|- ------|
| 1个|1个|1个|伊七九七|2023年1月2日|
| 1个|第二章|第二章|I94|2023年1月2日|
| 1个|三个|三个|一些其他值|2023年1月2日|
我想***只选择***DocumentType = 'I797'所在的行,如果没有'I797',我想***只选择***DocumentType = 'I94'所在的行;如果找不到这两个值中的任何一个,我想取所有具有DocumentType的其他值的行。
最好使用SQL Server。
我想我正在寻找一个XOR子句,但无法找出如何在SQL Server中执行该操作或获取所有其他值。

332nm8kg

332nm8kg1#

类似于@siggemannen答案

select top 1 with ties
    case when DocumentType='I797' then 1
         when DocumentType='I94' then 2
    else 3
    end gr
   ,docs.*
from docs
order by 
    case when DocumentType='I797' then 1
         when DocumentType='I94' then 2
    else 3
    end

最短:

select top 1 with ties
   docs.*
from docs
order by 
    case when DocumentType='I797' then 1
         when DocumentType='I94' then 2
    else 3
    end
k97glaaz

k97glaaz2#

大概是这样的:

select *
from (
    select t.*, DENSE_RANK() OVER(ORDER BY CASE WHEN DocumentType = 'I797' THEN 0 WHEN DocumentType = 'I94' THEN 1 ELSE 2 END) AS prioorder
    from 
    (
        VALUES  
            (1, 1, 1, N'I797', N'01/02/23')
        ,   (1, 2, 2, N'I94', N'01/02/23')
        ,   (1, 3, 3, N'Some Other Value', N'01/02/23')
        ,   (1, 4, 3, N'Super Sekret', N'01/02/23')
    ) t (CaseId,DocId,DocumentTypeId,DocumentType,ExpirationDate)
    ) x
WHERE   x.prioorder = 1

其思想是根据文档类型按1、2、3对行进行排序。由于我们对“其余行”的排序相同,因此如果I797和I94缺失,您将获得所有行。

2skhul33

2skhul333#

select * from YourTable where DocumentType = 'I797'
union 
select * from YourTable t where DocumentType = 'I94' and (not exists (select * from YourTable where DocumentType = 'I797'))
union
select * from YourTable t where (not exists (select * from YourTable where DocumentType = 'I797' or DocumentType = 'I94' ))

相关问题