sql - DB2 Group By but table 2 makes duplicates -


i'm trying query iseries db2 v6r1m0. test sql statements in system navigator before using them in ado.net.

i've traced issue down this, i'm not sure how fix it.

 select      a.id     , a.otherstuff     , max(a.date || ' ' || a.time) adatetime /* i'm sure it's not line */     , b.id     , b.city      , b.state     , max(b.date || ' ' || b.time) bdatetime      table1  inner join     table2 b on a.id = b.id  group    a.id, a.otherstuff, b.id, b.city, b.state  

what happens shows of b.cities , b.states, though want b.city , b.state max value.

 a.id    a.otherstuff    a.adatetime     b.id    b.city          b.state b.datetime   a.dup1  a.dup1          a.dup1          b.dup1  san francisco   ca      1-jan   1:00 a.dup1  a.dup1          a.dup1          b.dup1  sacramento      ca      1-jan   2:00 a.dup1  a.dup1          a.dup1          b.dup1  other cities    wa      11-jan  3:00 a.dup2  a.dup2          a.dup2          b.dup2  san francisco   ca      11-jan  1:00 a.dup2  a.dup2          a.dup2          b.dup2  sacramento      ca      11-jan  2:00 a.dup2  a.dup2          a.dup2          b.dup2  other cities    wa      11-jan  3:00 

why happening?

using group by, result set hold (one) line each unique combination of values in columns listed. so, unless selected , grouped columns in table1 hold identical values, end more single row without joining second table.

if just want b.city , b.state max value, need single out appropriate row(s) using where condition - suggested @mustaccio.

something along

select   a.id   , a.otherstuff   , a.date_time   , b.city   , b.state   , b.date_time   table1 inner join   table2 b on   a.id = b.id   b.date_time = (select max(date_time) table2) ; 

should provide that.

if want rather maximum date_time value table1 in result - no matter record coming, try

select   a.id   , a.otherstuff   , (select max(date_time) table1) a_max_date_time   , b.city   , b.state   , b.date_time b_date_time   table1 inner join   table2 b on   a.id = b.id   b.date_time = (select max(date_time) table2) ; 

see in action: sql fiddle. (sorry - no db2 in sql fiddle; , single date_time column each.)

please comment if , further detail / adjustment required. (sample data , expected output particularly helpful...)


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -