选择特定行但基于另一个列角色

问题描述 投票:1回答:5

我尝试并阅读了很多帖子,但我仍然无法弄清楚如何处理这个请求:

我有一张如下表

+-------+---------------+------------+
| 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      |
+-------+---------------+------------+
sql sql-server sql-server-2008 sql-server-2014
5个回答
0
投票

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

0
投票

嗯。 。 。我认为这样做你想要的:

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);

0
投票

如果您只有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

0
投票

如果你有其他功能,你应该添加到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

0
投票

根据我的理解

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

© www.soinside.com 2019 - 2024. All rights reserved.