我们有一个DB表,其中包含如下所示的公司职务代码:
ID Code Company
1 EW10 ***
2 EW10 DEU
3 EW10 DEC
4 EW20 ***
5 EW30 DEU
6 EW40 DEC公司中的“*”表示可以在雇主级别(DEU、DEC)覆盖的企业级职务代码。
我需要一个select语句,它返回具有以下条件的行:
我需要的结果集如下:
ID Code Company
2 EW10 DEU
3 EW10 DEC
4 EW20 ***
5 EW30 DEU
6 EW40 DEC发布于 2019-08-12 12:26:28
对于以下两种情况,您可以使用OR来完成此操作:
SELECT *
FROM YourTable yt1
WHERE Company <> '***'
OR NOT EXISTS (
SELECT 1 FROM YourTable yt2
WHERE yt2.Code = yt1.Code AND yt2.Company <> '***'
)发布于 2019-08-12 12:12:44
使用窗口函数。这比必要的要复杂一些,因为使用的是***而不是NULL。以下内容来回转换为NULL
select t.*,
coalesce(nullif(company, '***'),
max(nullif(company, '***')) over (partition by code),
'***'
)
from t;编辑:
您的问题是要返回所有行。但是,您的示例数据则不然。
我想你可能想:
select t.*
from t
where t.company <> '***' or
not exists (select 1
from t t2
where t2.code = t.code and
t2.company <> '***'
);或者,具有窗口功能:
select t.*
from (select t.*,
sum(case when company <> '***' then 1 else 0 end) over (partition by code) as num_notstars
from t
) t
where (num_notstars > 0 and company <> '***') or
(num_notstarts = 0);发布于 2019-08-12 12:19:04
与UNION ALL一起处理这2起案件:
select * from tablename
where Company <> '***'
union all
select * from tablename t
where not exists (
select 1 from tablename
where Code = t.Code and Company <> '***'
)
order by Id或者:
select * from tablename
where Company <> '***'
or Code in (
select Code from tablename
group by Code
having min(Company) = '***' and max(Company) = '***'
)见演示。
结果:
> ID | Code | Company
> -: | :--- | :------
> 2 | EW10 | DEU
> 3 | EW10 | DEC
> 4 | EW20 | ***
> 5 | EW30 | DEU
> 6 | EW40 | DEC https://stackoverflow.com/questions/57460948
复制相似问题