简体   繁体   English

选择所有行,但在新列中显示表中的最大值

[英]Select all rows but show the max value from the table in a new column

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 : 您可以使用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 

FIDDLE DEMO FIDDLE DEMO

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM