SQL选择组中的特定值

时间:2018-04-17 15:09:13

标签: sql oracle

我有以下表格

Dept----------  Sub_Dept----      Dept Type    
Sales.............Advertising........A    
Sales.............Marketing......... B    
Sales.............Analytics.......... C
Operations.....IT..................... C    
Operations.....Settlement........C

结果应该是一个部门的部门类型为A然后将该部门的所有记录更改为A,否则保持相同

Dept----------  Sub_Dept----      Dept Type    
Sales.............Advertising........A   
Sales.............Marketing......... A    
Sales.............Analytics.......... A    
Operations.....IT..................... C    
Operations.....Settlement........C

有人可以就此提出建议吗?我想过使用GROUP BY但是也必须输出Sub Department

非常感谢

5 个答案:

答案 0 :(得分:2)

我愿意:

update t
    set depttype = 'a'
    where exists (select 1 from t t2 where t2.dept = t.dept and t2.dept = 'a') and
          t.dept <> 'a';

如果您只想要select,请执行以下操作:

select t.*,
       (case when sum(case when depttype = 'a' then 1 else 0 end) over (partition by dept) > 1
             then 'a'
             else depttype
        end) as new_depttype
from t;

答案 1 :(得分:0)

试试这个:

update table
set depttype= case when dept in (select dept from table where depttype='a') then 'a' else depttype end 

答案 2 :(得分:0)

使用以下查询

select a11.dept, a12.Sub_Dept, (case when a12.min_dep_type='A' then 'A' else a11.dep_type) as dep_type
from tab a11
JOIN (select dept, min(dep_type) min_dep_type from tab group by dept) a12
on a11.dept = a12.dept

答案 3 :(得分:0)

这应该有效:

select a.dept, a.sub_dept, 
case when b.dept is not null then 'A' else dept_type end as dept_type
from aTable a
left join(
    select distinct Dept from aTable where dept_type = 'A'
) 
b on b.dept = a.dept

答案 4 :(得分:0)

您可以使用分析函数来检查组中是否存在特定值。

尝试以下查询:

SELECT t.Dept,
       t.Sub_Dept,
       NVL(MIN(CASE WHEN t.Dept_Type = 'A'
               THEN Dept_Type END) OVER (PARTITION BY t.Dept), t.Dept_Type) AS Dept_Type
  FROM table_1 t

使用分析函数MIN(),您可以搜索&#39; A&#39;的值。 (如果它确实存在于组内)。 MIN仅适用于非空值,因此如果您没有任何&#39; A&#39;在组中,结果将为NULL。

此时,您可以使用NVL选择是否打印组中找到的值或行的实际dept_type。