简体   繁体   中英

select max value of one column from multiple values of another field

Using Advantage Architect, I have a table that has two columns, Say IDENT and DATE for example. Each DISTINCT IDENT may have multiple DATE values against it, so a row per IDENT and DATE if SELECT * is performed. However, although I can use the below code to get the MAX DATE value for each IDENT, there are going to be instances in this table where the DATE value is NULL, and I don't want any results where there is any DATE against a given IDENT that is null. So, in effect, I only want my statement to show results where the only MAX DATE values against an IDENT are from DATES against IDENTs where there are not null DATEs. Any ideas?

Table Example:

IDENT | DATE
0001  | 19/12/2011
0001  | 30/12/2011
0001  | NULL
0002  | 01/01/2012
0002  | 30/01/2012 

Code I have so far:

select ident, max(date)
from Table A
group by ident;

Required Output:

IDENT | DATE
0002  | 30/01/2012 

Do the GROUP BY as before, use HAVING to exclude idents having a null value date.

select ident, max(date)
from Table A
group by ident
having count(date) = count(*)

Will work since count(date) counts non-null dates, but count(*) counts all rows.

For ident 0001 count(date) = 2 , but count(*) = 3 . Ie not returned.

For ident 0002 count(date) = 2 , and count(*) = 2 . Ie returned.

Not sure if I understood your question, but you want to exclude the idents for which at least 1 row with a NULL date exists.

Try this:

SELECT   a.ident,
         MAX(a.date)
FROM     Table a
WHERE    NOT EXISTS (SELECT *
                     FROM   Table b
                     WHERE  a.ident = b.ident
                       AND  b.date IS NULL)
GROUP BY a.ident;

I appear to have overlooked an extra detail here, in that as part of the select statement from Table, I want the associated value of another column brought in. So, it'll be IDENT, DATE,REF, with REF being associated to the IDENT and the MAX DATE that's been brought through. I don't seem to be able to do this however, as REF isn't in the GROUP BY part, and when I do add it as part of the GROUP BY, it distorts my results.

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