Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

take only one record of select

Tags:

sql

db2

I need to fetch only first record (because I need last date) of resultset, at the moment I have this resultset from this sql tring:

SELECT BCACC,FLDAT
FROM ANAGEFLF
ORDER BY FLDAT DESC

and I see this record:

A.M.T. AUTOTRASPORTI SRL        20080220
A.M.T. AUTOTRASPORTI SRL        20080123
A.M.T. AUTOTRASPORTI SRL        20070731
APOFRUIT ITALIA                 20080414
APOFRUIT ITALIA                 20080205
APOFRUIT ITALIA                 20071210
APOFRUIT ITALIA                 20070917
APOFRUIT ITALIA                 20070907

now I need to take only one record (first) for every BCACC, I would take this resultset:

A.M.T. AUTOTRASPORTI SRL        20080220
APOFRUIT ITALIA                 20080414

I've just try group it for BCACC but I receive an sql error, I'm workin on DB2 ibmI

like image 692
jack.cap.rooney Avatar asked Mar 21 '12 15:03

jack.cap.rooney


2 Answers

Assuming they are the only fields involved, you can just do a GROUP BY.

SELECT
  BCACC,
  MAX(FLDAT) AS FLDAT
FROM
  ANAGEFLF
GROUP BY
  BCACC

If, however, you have other fields that you need, then you just join this back of the table as a sub-query...

SELECT
  ANAGEFLF.*
FROM
  ANAGEFLF
INNER JOIN
(
  SELECT
    BCACC,
    MAX(FLDAT) AS FLDAT
  FROM
    ANAGEFLF
  GROUP BY
    BCACC
)
  AS map
    ON  map.BCACC = ANAGEFLF.BCACC
    AND map.FLDAT = ANAGEFLF.FLDAT
like image 169
MatBailie Avatar answered Sep 22 '22 19:09

MatBailie


select BCACC, max(FLDAT)
from ANAGEFLF
group by BCACC
like image 28
Christopher Weiss Avatar answered Sep 18 '22 19:09

Christopher Weiss