Warm tip: This article is reproduced from serverfault.com, please click

sql-具有多个条目的条件的Select语句

(sql - Select statement with a condition on multiple entries)

发布于 2020-11-30 07:22:58

以下是我的桌子:

在此处输入图片说明

我想在select语句中创建一个具有以下条件的视图:

如果count(employee_id)> 1,则仅在视图中选择状态为'Current'的记录。

我试过:

select employee_id
    , case when COUNT(employee_id) > 1 and statusval = 'Current' then 'Y' else 'N' end as val
from table1
group by employee_id

我希望有人可以帮助我发表这一声明。谢谢。

Questioner
NotRoboSQl
Viewed
11
Dale K 2020-11-30 15:57:51

只是为了向你展示你的尝试看起来如何。你已经快到了,你只需要使用count例如的窗口版本

with cte as (
    select Employee_Id, [Status]
        , case when count(*) over (partition by id) > 1 and [Status] = 'Current' then 1 else 0 end Val
    from Table1
)
select Employee_Id, [Status]
from cte
where Val = 1;

从表面上看,这种方法比连接要好。