我有这个数据
ID Name State Check
1 Raj UP ok
1 Raj UP Notok
2 bob MP ok
2 bob MP ok
3 joy MH Notok
3 joy MH Notok
我想要关注数据
ID Name State Check flag
1 Raj UP ok y
1 Raj UP Notok n
2 bob MP ok y
2 bob MP ok n
3 joy MH Notok y
3 joy MH Notok n
我想确定哪个被选中。
答案 0 :(得分:2)
您应该指定规则,但看起来任何ok
都会命名为ok
:
select id, name, state,
(case when sum(case when [check] = 'ok' then 1 else 0 end) > 0
then 'ok'
else 'Notok'
end) as [check]
from t
group by id, name, state;
注意:check
是SQL中的关键字,因此它是列的错误名称。在您的情况下,您也可以这样做:
select id, name, state, min(lower([check])) as [check]
from t
group by id, name, state;
此版本使用逻辑值的字母顺序。
答案 1 :(得分:0)
create table #Temp (ID int, Name Varchar(8000), State char(2), [Check] varchar(8000))
Insert #Temp Values (1, 'Raj', 'UP', 'ok')
Insert #Temp Values (1 ,'Raj', 'UP', 'Notok')
Insert #Temp Values (2 ,'bob', 'MP', 'ok')
Insert #Temp Values (2 ,'bob', 'MP', 'ok')
Insert #Temp Values (3 ,'joy', 'MH', 'Notok')
Insert #Temp Values (3 ,'joy', 'MH', 'Notok')
;With cteRowsAssigned AS
(
Select Row_Number() Over (Partition By Name Order By [Check] Desc) RowNum,
*
From #Temp
)
Select ID, Name, State, [Check] From cteRowsAssigned Where RowNum = 1 Order By ID
答案 2 :(得分:0)
如果您的意思是ok
优先于Notok
select id, name, state, case when max(
case when [check] = 'ok' then 1 else 0 end) = 1
then 'ok'
else 'Notok'
end as [check]
from table
group by id, name, state;
答案 3 :(得分:0)
最简单的形式是:
SELECT id,name,state FROM t where <whatever filter you want to set> GROUP BY id,name,state