I'm doing a select and i want to highlight any rows that have the most recent date. This is not per group but across the entire returned table.
I still want to retrieve all the rows in table regardless of whether they are the max or not, but i want to ensure that we can find the latest values subset of the table. Preferably a new column with a flag or the actual value in it.
How would I go about this?
Current table (example)
+----+-------------+
| Id | Date |
+----+-------------+
| 1 | 1 Jan 2012 |
| 2 | 3 Jan 2012 |
| 3 | 2 Jan 2012 |
| 3 | 5 Jan 2012 |
| 4 | 5 Jan 2012 |
+----+-------------+
Ideal output
+----+-------------+---------+
| Id | Date | Latest? |
+----+-------------+---------+
| 1 | 1 Jan 2012 | no |
| 2 | 3 Jan 2012 | no |
| 3 | 2 Jan 2012 | no |
| 3 | 5 Jan 2012 | yes |
| 4 | 5 Jan 2012 | yes |
+----+-------------+---------+
You can join the table with its MAX
:
SELECT my_table.*, CASE WHEN date = max_date THEN 'yes' ELSE 'no' END AS latest
FROM my_table
JOIN (SELECT MAX(date) AS max_date FROM my_table) t -- Note it's only one row, no need for a join condition
Try like this
SELECT ID,DATE,
CASE WHEN DATE = (SELECT MAX(DATE) FROM TABLE1) Then 'YES' ELSE 'No' END LATEST
FROM TABLE1 T1
TRY this, I've separated the maximum date so it only get the max date once and used it in the main query.
DECLARE @MaxDate As DateTime
SELECT @MaxDate = MAX(DATE) FROM TABLE1
SELECT ID,
DATE,
CASE WHEN DATE = @MaxDate Then 'yes' ELSE 'no' END Lates
FROM TABLE1
ORDER BY ID, DATE
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.