选择特定行但基于另一个列角色
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了选择特定行但基于另一个列角色相关的知识,希望对你有一定的参考价值。
我尝试并阅读了很多帖子,但我仍然无法弄清楚如何处理这个请求:
我有一张如下表
+-------+---------------+------------+
| ID | Comp. | Role |
+-------+---------------+------------+
| 1 | abc | All |
+-------+---------------+------------+
| 1 | abc | Sales |
+-------+---------------+------------+
| 2 | def | All |
+-------+---------------+------------+
| 3 | zeh | All |
+-------+---------------+------------+
| 3 | zeh | TI |
+-------+---------------+------------+
我想基于结果角色,如果一个特定的id有两个角色,一个是All,而另一个是Sales,那么我需要考虑Sales行
输出应该是这样的
+-------+---------------+------------+
| ID | Comp. | Role |
+-------+---------------+------------+
| 1 | abc | Sales |
+-------+---------------+------------+
| 2 | def | All |
+-------+---------------+------------+
| 3 | zeh | TI |
+-------+---------------+------------+
答案
UNION ALL将取代这个地方
select * from table
where role <> 'All'
union all
select * from table t
where not exists (
select 1 from table
where id = t.id and [comp.] = t.[comp.] and role <> 'All'
)
order by 1
结果:
ID Comp. Role
1 abc Sales
2 def All
3 zeh IT
另一答案
嗯。 。 。我认为这样做你想要的:
select t.*
from t
where t.role = 'Sales'
union all
select t.*
from t
where t.role <> 'Sales' and
not exists (select 1 from t t2 where t2.id = t.id);
另一答案
如果您只有2个Role值('Sales'和'All'),这将有效
create table #tmp(ID INT,Comp VARCHAR(10),Role VARCHAR(10))
insert into #tmp
SELECT 1,'abc','All'
union ALL
SELECT 1,'abc','Sales'
union ALL
SELECT 2,'def','All'
select ID,Comp,MAX(Role) As Role from #tmp
Group by Id,comp
drop table #tmp
另一答案
如果你有其他功能,你应该添加到CASE WHEN
SELECT
ID
, Comp
, CASE WHEN role_id = 0 THEN 'All'
WHEN role_id = 1 THEN 'Sales'
WHEN role_id = 2 THEN 'TI'
ELSE NULL END AS Role
FROM
(
SELECT
ID
, Comp
, MAX(CASE WHEN Role = 'All' THEN 0
WHEN Role = 'Sales' THEN 1
WHEN Role = 'TI' THEN 2 END
ELSE -1 END) AS role_id
FROM
t
GROUP BY
ID
, Comp
)tmp
另一答案
根据我的理解
SELECT ID,Comp,Role
FROM table1
WHERE ID IN(SELECT ID FROM table1 GROUP BY ID) AND Role != 'All'
UNION
SELECT ID,Comp,Role
FROM table1
WHERE ID IN(SELECT ID FROM table1 GROUP BY ID HAVING COUNT(ID)=1)
这工作正常检查这demo
以上是关于选择特定行但基于另一个列角色的主要内容,如果未能解决你的问题,请参考以下文章