下面是我的表格:

我想在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我希望有人能帮我解决这个问题。谢谢。
发布于 2020-11-30 15:57:52
只是想让你看看你的尝试会是什么样子。你就快成功了,你只需要使用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;从表面上看,这种方法比join执行得更好。
发布于 2020-11-30 15:34:16
尝尝这个
DECLARE @T TABLE (ID INT, STATUS VARCHAR(50))
INSERT INTO @T VALUES (1,'Current'),(2,'Historical'),(2,'Historical'),(2,'Current')
SELECT * FROM @T M
INNER JOIN (SELECT ID FROM @T
GROUP BY ID
HAVING COUNT(ID) > 1) S ON S.ID=M.ID
WHERE M.STATUS = 'Current'发布于 2020-11-30 21:07:04
您的所有示例数据都恰好有一行包含'Current'。因此,最简单的解决方案似乎是:
select t.*
from t
where t.status = 'Current';https://stackoverflow.com/questions/65069470
复制相似问题