0

I am trying to get a row from SQL db, which meets 2 conditions :

1) Value 1 == 'A'

AND

2) date is MAX

----------------------------------------------
|                 Log                        |
----------------------------------------------
|  date   |     value 1     |     Value 2    |
----------------------------------------------
|  1000   |        A        |       C        |
|  1100   |        A        |       C        |
|  1200   |        B        |       C        |
----------------------------------------------

I can get the max value with following query :

SELECT *
FROM log
INNER JOIN(
   SELECT MAX(date) date 
   FROM log
)MaxDate
ON MaxDate.date = log.date

How can i add 1st condition to this query?

2
  • 2
    Tag your question with the database you are using. Commented Feb 1, 2020 at 0:17
  • The answer would be strongly specific to what DBMS are you using. Commented Feb 1, 2020 at 8:34

2 Answers 2

1

Use order by and limit to one row:

select l.*
from logs l
where l.value = 'A'
order by l.date desc
fetch first 1 row only;

Not all databases support fetch first. It might be limit or top (1), for instance.

Sign up to request clarification or add additional context in comments.

Comments

0

Assuming you want the row where the date is max among those rows with value1 = 'A', the following should work across all DBMSs and be easy to tweak:

SELECT *
FROM log
INNER JOIN(
   SELECT value1, MAX(date) date 
   FROM log
   GROUP BY value1
) MaxDate
ON MaxDate.date = log.date and MaxDate.value1 = log.value1
WHERE log.value1 = 'A'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.