column1 column2 column3 Column4A 10 am 1999-01-01 00:00:00.000a 11 am 1999-01-02 00:00:00.000b 12 BM 1999-01-03 00:00:00.000b 13 bm 1999-01-04 00:00:00.000c 14 cm 1999-01-05 00:00:00.000c 15 cm   1999-01-06 00:00:00.000
Request data:
column1 column2 column3 Column4A 11 am 1999-01-02 00:00:00.000b 13 bm 1999-01-04 00:00:00.000c 15 cm 1999-01-06 00:00:00.000
--Data loading
Create Table #T (Column1 varchar), Column2 int,column3 varchar (a), Column4 datetime) Insert #T Select ' A ', ' am ', ' 1999-1-1 ' UNION ALL Select ' A ', one, ' am ', ' 1999-1-2 ' union ALL select ' B ', one, ' bm ', ' 1999-1-3 ' union ALL select ' B ', ', ' BM ', ' 1999-1-4 ' UNION ALL SELECT ' C ', M, ' cm ', ' 1999-1-5 ' union ALL SELECT ' C ', ' cm ', ' 1999-1-6 '
--Test Statement Method 1:
Select A.* from #T a WHERE (A.COLUMN4) = (select top 1 (Column4) to #T where Column1 = a.column1 ORDER by Column4 des C
--Test results:
column1 column2 column3 Column4 -------------------------------------------------------------- -----------------------a 11 am 1999-01-02 00:00:00.000b 13 bm 1999-01-04 00:00:00.000c 15 cm 1999-01-06 00:00:00.000
--Test Statement Method 2: (Best efficiency)
Select A.* from #T a join (select Column1,column4=max (COLUMN4) to #T Group by Column1) B on A.column1=b.column1 and a.co Lumn4=b.column4order by A.column1
--Test Results Method 2:
column1 column2 column3 Column4 -------------------------------------------------------------- -----------------------a 11 am 1999-01-02 00:00:00.000b 13 bm 1999-01-04 00:00:00.000c 15 cm 1999-01-06 00:00:00.000
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.