Select 具有多个条目条件的语句
Select statement with a condition on multiple entries
以下是我的table:
我想在 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
我希望有人能帮我解决这个问题。谢谢
试试这个
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'
只是为了向您展示您的尝试可能是什么样子。你快到了,你只需要使用 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;
从表面上看,这种方法比联接执行得更好。
您的所有示例数据都只有一行 'Current'
。因此,最简单的解决方案似乎是:
select t.*
from t
where t.status = 'Current';
以下是我的table:
我想在 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
我希望有人能帮我解决这个问题。谢谢
试试这个
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'
只是为了向您展示您的尝试可能是什么样子。你快到了,你只需要使用 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;
从表面上看,这种方法比联接执行得更好。
您的所有示例数据都只有一行 'Current'
。因此,最简单的解决方案似乎是:
select t.*
from t
where t.status = 'Current';