简体   繁体   English

如何在SQL Server中按列按max(date)组获取数据

[英]How to get data by max(date) group by column in SQL Server

In the table below I need lastservice data based on the last date group by nopol. 在下表中,我需要基于lastservice的最后日期分组的lastservice数据。

Table data: 表格数据:

在此处输入图片说明

I tried to use the query below 我尝试使用下面的查询

SELECT 
    TGL, A.NOPOL, LASTSERVICE 
FROM 
    TRREALPRWT AS A
INNER JOIN 
    (SELECT 
         MAX(TGLREAL) AS TGL, NOPOL 
     FROM 
         TRREALPRWT 
     GROUP BY 
         NOPOL) AS B ON B.NOPOL = A.NOPOL
GROUP BY 
    A.NOPOL, TGL,LASTSERVICE

but the results obtained are not per nopol. 但是获得的结果并非每个诺普。

What I should do from the query so that it produces data like the following 我应该从查询中做什么,以便它产生如下数据

| NOPOL   | LASTSERVICE | TGLREAL                   |
| L9235VB | 224270      | 2018-01-26 00: 00: 00.000 |
| B9891JT | 219270      | 2018-02-28 00: 00: 00.000 |

I believe this should work, assuming TGLREAL is your date. 我相信这应该可行,假设TGLREAL是您的约会对象。

SELECT TGL,A.NOPOL,LASTSERVICE FROM TRREALPRWT
WHERE TGLREAL IN (SELECT MAX(TGLREAL) FROM  TRREALPRWT)

Is seems to be use only group by clause no need to inner query 似乎只使用group by子句而无需内部查询

select nopol, min(LASTSERVICE) LASTSERVICE, max(TGL) TGLREAL  
from TRREALPRWT 
group by nopol

Take all MAX(TGL) for all NOPOL in an inner query and join it again with your original table matching on NOPOL and MAX(TGL) values. 在内部查询中获取所有NOPOL所有MAX(TGL) ,然后将其与原始表匹配,再次匹配NOPOLMAX(TGL)值。

SELECT T.NOPOL, T.TGL, T.LASTSERVICE
FROM
YOUR_TABLE T
INNER JOIN
(SELECT NOPOL, MAX(TGL) AS MAX_TGL FROM YOUR_TABLE GROUP BY NOPOL) A
ON T.NOPOL = A.NOPOL AND T.TGL = A.MAX_TGL;

The sample output in the question seems to indicate that you want the first tgl for each nopol, max(lastservice) 问题中的样本输出似乎表明您想要每个nopol的第一个tgl,max(lastservice)

SELECT nopol,MIN(lastservice) lastservice,  MAX(tgl) tglreal
FROM trreal
GROUP BY nopol 

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

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