在编写SQL查询时需要帮助

时间:2016-09-22 08:37:51

标签: sql oracle

我有一个要求,例如,在表格中有列和值,如下所示

Emp ID  Address Department  Supervisior ID
1001    Chennai Science     123
1001    Chennai Science     124
1001    Chennai Science     125
1002    Chennai Science     128
1003    Chennai Science     123
1003    Chennai Science     124
1003    Chennai Science     126
1004    Bangalore  Science  129 
1005    Mumbai  Science    130
1005    Mumbai  Science    131
1005    Mumbai  Science    132

从I / p表中,我将提示Supervisior id(即Supervisior id为123)。如果我提示,我的查询输出应为

Emp ID  Address Department  Supervisior ID
1001    Chennai Science 123
1002    Chennai Science 128
1003    Chennai Science 123
1004    Bangalore   Science 129
1005    Mumbai  Science 130

要求是,如果我提示Supervisior id 123,我必须从表中选择所有具有supervisior Id的记录为123.但前三个记录是相同的,唯一的区别是supervisior id。所以我不想要第二和第三行。

另外,我想要其他记录,其中supervisior id不等于123.所以我想要第4行和第8行。但是最后三行是相同的,唯一的区别是supervisior id。从最后三个开始,我只想要一行(即第9行)。

我尝试使用union查询和完全外连接。 Nothings对我有用。

2 个答案:

答案 0 :(得分:0)

使用“group by”&您的查询中的“min”如下所示。

/****** Dataset ****************/
with tabl(Emp_ID, Address, Department, Supervisior_ID) as
 ( select 1001 , 'Chennai', 'Science' ,   123  from dual
   UNION ALL
   select 1001 , 'Chennai', 'Science' ,   124  from dual
   UNION ALL
   select 1001 , 'Chennai', 'Science' ,   125  from dual
   UNION ALL
   select 1002 , 'Chennai', 'Science' ,   128  from dual
   UNION ALL
   select 1003 , 'Chennai', 'Science' ,   123  from dual
   UNION ALL
   select 1003 , 'Chennai', 'Science' ,   124  from dual
   UNION ALL
   select 1003 , 'Chennai', 'Science' ,   126  from dual
   UNION ALL
   select 1004 , 'Bangalore', 'Science' ,   129  from dual
   UNION ALL
   select 1005 , 'Mumbai', 'Science' ,   130  from dual
   UNION ALL
   select 1005 , 'Mumbai', 'Science' ,   131  from dual
   UNION ALL
   select 1005 , 'Mumbai', 'Science' ,   132  from dual )
 /********You Main query goes from here *************/  
select emp_id,Address, Department, min(Supervisior_ID)
 from tabl
 group by emp_id,Address, Department
 order by 1;

答案 1 :(得分:0)

MIN就是你要找的。

SELECT EMP_ID,
       ADDRESS,
       DEPARTMENT,
       NVL(
            MIN(DECODE(SUPERVISOR_ID,:L_SUPERVISOR_ID,SUPERVISOR_ID)),
            MIN(SUPERVISOR_ID)
           ) AS SUPERVISOR_ID
FROM YOUR_TABLE
GROUP BY EMP_ID,ADDRESS,DEPARTMENT
ORDER BY EMP_ID,ADDRESS,DEPARTMENT,SUPERVISOR_ID;

这里的诀窍是MIN(DECODE(SUPERVISOR_ID,:L_SUPERVISOR_ID,SUPERVISOR_ID))

当没有匹配的ID时,这将是NULL,因此在这种情况下只需执行MINNVL照顾它。

如果该组中有匹配的主管ID,则会立即返回。