LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   db2 SQL question (https://www.linuxquestions.org/questions/programming-9/db2-sql-question-4175558024/)

Jerry Mcguire 11-05-2015 01:27 AM

db2 SQL question
 
Not sure if this is a programming question.

I have 2 tables with the following content

Code:

$ db2 "select * from C"

FRUIT    SN
-------  --
apple    4
apple    5
apple    6
banana  22
banana  23

5 records selected

$ db2 "select fruit, min(sn) as min_sn from U group by fruit"

FRUIT    MIN_SN
-------  ------
apple        7
banana      15
pear        88

3 records selected

Note that 'pear' does not appear in table C.
Table U contains all fruit entries in this universe.

I want to count each type of fruit (apple, banana, pear) in table C that has Serial Number (SN) smaller than the MIN_SN returned from the 2nd query. Is there is efficient way to do it? The tricky part is that the banana and pear count should be 0.

Code:

$ db2 "
select fruit, count(sn) as count
from (
  select MU.fruit, C.sn
  from C
  right join (select fruit, min(sn) as min_sn from U group by fruit) MU
  on C.fruit = MU.fruit
  where C.sn < MU.min_sn
)
group by fruit"

FRUIT    COUNT
-------  -----
apple        3

1 records selected

The above query only shows apple having 3 counts, but no banana or pear. So a union is added:

Code:

$ db2 "
select *
from (
  select fruit, count(sn) as count, min_sn
  from (
    select MU.fruit, C.sn, MU.min_sn
    from C
    right join (select fruit, min(sn) as min_sn from U group by fruit) MU
    on C.fruit = MU.fruit
    where C.sn < MU.min_sn
  )
  group by fruit, min_sn
)
union
(
  select fruit, 0 as count, min(sn) as min_sn
  from U
  where not exists (select 1
                    from C
                    where fruit = U.fruit)
  group by fruit
)
order by fruit"

FRUIT    COUNT  MIN_SN
-------  -----  ------
apple        3      7
banana      0      15
pear        0      88

3 records selected

This is quite clumsy, don't you think?

dr_agon 11-21-2015 04:03 PM

I would just nest the SELECTs like this:

Code:

select
  fruit,
  min(sn) as min_sn,
  (select count(C.sn) from C where C.fruit = U.fruit and C.sn < min(U.sn) ) as C_count
from U
group by fruit

Look at the example for Postgres (I do not know db2): http://sqlfiddle.com/#!15/7bf9f/20

Jerry Mcguire 11-23-2015 02:11 AM

Right. Thanks. I didn't know sub-SELECT could go right after SELECT.


All times are GMT -5. The time now is 10:36 PM.