使用以下数据......
+--------------+--------+---------------+-----------------+----------------+
| EQUIPMENT_ID | CML_ID | INSPECTION_NO | INSPECTION_DATE | WALL_THICKNESS |
+--------------+--------+---------------+-----------------+----------------+
| B1000-V001 | 1 | 1 | 1/01/2016 | 10 |
| B1000-V001 | 1 | 2 | 2/01/2016 | 9 |
| B1000-V001 | 1 | 3 | 3/01/2016 | 3 |
| B1000-V001 | 1 | 4 | 4/01/2016 | 7 |
| B1000-V001 | 1 | 5 | 5/01/2016 | 5 |
| B1000-V001 | 1 | 6 | 6/01/2016 | 4 |
| B1000-V001 | 1 | 7 | 7/01/2016 | 4 |
| B1000-V001 | 1 | 8 | 8/01/2016 | 8 |
| B1000-V001 | 1 | 9 | 9/01/2016 | 17 |
| B1000-V001 | 1 | 10 | 10/01/2016 | 5 |
| B1000-X123 | 5 | 1 | 1/01/2016 | 2 |
| B1000-X123 | 5 | 2 | 2/01/2016 | 8 |
| B1000-X123 | 5 | 3 | 3/01/2016 | 4 |
| B1000-X123 | 5 | 4 | 4/01/2016 | 5 |
| B1000-X123 | 5 | 5 | 5/01/2016 | 7 |
| B1000-P789 | 3 | 1 | 1/01/2016 | 8 |
| B1000-P789 | 3 | 2 | 2/01/2016 | 7 |
| B1000-P789 | 3 | 3 | 3/01/2016 | 5 |
| B1000-P789 | 3 | 4 | 4/01/2016 | 1 |
| B1000-P789 | 3 | 5 | 5/01/2016 | 4 |
+--------------+--------+---------------+-----------------+----------------+
我希望以最快的方式产生以下结果......
+--------------+--------+---------------+-----------------+----------------+
| EQUIPMENT_ID | CML_ID | INSPECTION_NO | INSPECTION_DATE | WALL_THICKNESS |
| B1000-V001 | 1 | 10 | 10/01/2016 | 5 |
| B1000-P789 | 3 | 5 | 5/01/2016 | 4 |
| B1000-X123 | 5 | 5 | 5/01/2016 | 7 |
+--------------+--------+---------------+-----------------+----------------+
即。 GROUP BY EQUIPMENT_ID,CML_ID并始终返回与最大检验编号相关联的记录。
答案 0 :(得分:0)
尝试以下查询。
Select a.Equipment_ID, a.CML_ID, b.INSPECTION_NO,a.INSPECTION_DATE, a.WALL_THICKNESS
from
#YourTable a inner join
(
Select Equipment_ID, CML_ID, max(INSPECTION_NO)as INSPECTION_NO
from #YourTable
Group By Equipment_ID,CML_ID
) b
on a.Equipment_ID=b.Equipment_ID and a.CML_ID=b.CML_ID and a.INSPECTION_NO=b.INSPECTION_NO
order by a.Equipment_ID
SQL_FIDDLE:DEMO
如果您有任何问题或疑虑,请告诉我们。