我要选择有条件的数据
我有一张桌子
Id|Name |Age
1 |David |1
2 |Aic |2
3 |Owen |2
4 |Aic |3
5 |Phuc |3
6 |Aic |4
7 |Ronaldo |4
8 |Ronaldo |5
9 |Ronaldo |6
我如何查询2条记录是否具有与2相同的年龄,它将只选择名称为“ aic”的记录,否则将获得全部(如果不相同的年龄将得到所有类似的图像)
Id|Name |Age
1 |David |1
2 |Aic |2
4 |Aic |3
6 |Aic |4
8 |Ronaldo |5
9 |Ronaldo |6
答案 0 :(得分:1)
您可以尝试使用row_number()
select id,name,age from
(
select id,name,age,row_number() over(partition by age order by name) as rn
from tablename
)A where rn=1
输出:
d name age
1 David 1
2 Aic 2
4 Aic 3
6 Aic 4
8 Ronaldo 5
9 Ronaldo 6
答案 1 :(得分:0)
**您可以使用此** row_number()
,而test1
是您的表格名称
select id,name,age from ( select id,name,age,row_number()
over(partition by age order by name) as rownumber from test1 )A where rownumber=1
答案 2 :(得分:0)
一种简单的方法是:
select t.*
from t
where t.name = 'Aic'
union all
select t.*
from t
where t.name <> 'Aic' and
not exists (select 1 from t t2 where t2.age = t.age and t2.name = 'Aic');
这将选择所有“ Aic”,然后选择所有其他没有Aic的年龄。实际上,这可以组合成一个查询:
select t.*
from t
where t.name = 'Aic' or
(t.name <> 'Aic' and
not exists (select 1 from t t2 where t2.age = t.age and t2.name = 'Aic')
);
如果您想使用窗口功能,我可能会建议:
select t.*
from (select t.*,
sum(case when name = 'Aic' then 1 else 0 end) over (partition by age) as num_aic
from t
) t
where name = 'Aic' or num_aic = 0
答案 3 :(得分:-1)
随着您更改问题,请使用子查询
select * from table where age in ( select age from table where name ='Aic')
当您再次更改问题时,它就会变成
with cte as (
select *,
row_number() over(partition by age order by name) as rn
from table
) select * from cte where rn=1