简体   繁体   中英

subquery to derive a value if all values of the column is the same for

Hi i have a situation here with Oracle SQL to come out with the sql result as the following :-

Company    No of Employees    Group      Derived Field
   a               1            x 
   b               1            x  
   c               2            y 
   d               1            y

so based on the group if all the company has same no of employees then i want the derived field to be true else false.

So for group x , if company a and b has the same no of employees then derived field for a and b would be true. As for c and d because the no of employees is different so the derived field should be false.

any help would be appreciated. thanks

You want to use an analytic function. I think this is what you want:

select t.*,
       (case when min(NumEmployees) over (partition by grp) =
                  max(NumEmployees) over (partition by grp)
             then 1
             else 0
        end) as DerivedField
from table t;

Note: I usually represent booleans as 0 and 1.

Here is a purely sql solution. Assume the column names are company,number,ggroup,test.

for convenience create a view of table t as

create view gnums as select count(distinct number)as gnum,count(number) as num, ggroup from t group by ggroup;

The this select

select a.*,b.gnum = 1 and b.num <> 1 as test from ta,gnums b where a.ggroup = b.ggroup;

yields

 id | company | number | ggroup | test
----+---------+--------+--------+------
  1 | a       |      1 | x      | t
  2 | b       |      1 | x      | t
  3 | c       |      2 | y      | f
  4 | d       |      1 | y      | f
  5 | e       |      2 | z      | f

I added row e to show that any group with only one company should yield false, assuming that's what you intended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM