如何在 SQL 服务器 SELECT 中 Select 第二个加入 Table 中的每条记录的顶部?

How To Select One Top Of Each Record By Id in Second Joined Table In SQL Server SELECT?

这是我的代码

SELECT DISTINCT
   E.EquipmentId, E.Name, E.KakhdaryNo, E.PropertyNo, 
   E.InstallationPlace, E.InstallationDate, E.BuyDate,
   Vt.TypeCaption, E.VisitChosen, E.LastVisitDate, V.VisitReport
FROM 
   TblEquipment E 
LEFT JOIN 
   TblVisitType Vt ON E.VisitType = Vt.VisitTypeId 
LEFT JOIN 
   TblVisit V ON E.EquipmentId = V.EquipmentId 
WHERE 
   1=1 
   AND E.Deleted <> 'True'
GROUP BY 
   E.Name

我收到一个错误:

Msg 8120, Level 16, State 1, Line 1
Column 'TblEquipment.EquipmentId' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

如果我不使用 group by 结果如下:

所以你可以看到设备 ID 15 是重复的..我只想要其中之一..我更喜欢上面的那个,我的意思是较新的记录

请帮我看看怎么做?

正如我在评论中提到的,您正在选择一堆 non aggregated column's 并在 group by 中只保留一个,这在 Sql Server 中是不允许的。要删除重复行,请使用 row_number window 函数。

同时删除 where 子句中不需要的 1=1 条件。

如果我没记错的话,这就是您要找的。

SELECT EquipmentId,
       NAME,
       KakhdaryNo,
       PropertyNo,
       InstallationPlace,
       InstallationDate,
       BuyDate,
       .TypeCaption,
       VisitChosen,
       LastVisitDate,
       VisitReport
FROM   (SELECT Row_number()OVER(partition BY E.EquipmentId ORDER BY order_by_column) AS RN,
               E.EquipmentId,
               E.NAME,
               E.KakhdaryNo,
               E.PropertyNo,
               E.InstallationPlace,
               E.InstallationDate,
               E.BuyDate,
               Vt.TypeCaption,
               E.VisitChosen,
               E.LastVisitDate,
               V.VisitReport
        FROM   TblEquipment E
               LEFT JOIN TblVisitType Vt
                      ON E.VisitType = Vt.VisitTypeId
               LEFT JOIN TblVisit V
                      ON E.EquipmentId = V.EquipmentId
        WHERE  E.Deleted <> 'True') A
WHERE  RN = 1 

Aa you are using Group By clause so you have to use Aggregate function for each selecting column or you have to use the column in Group By clause

例如

select a,b,max(c),min(d) from  table_Name group by a,b

你的情况

SELECT 
Max(E.EquipmentId),
E.Name,
Max(E.KakhdaryNo),
Max(E.PropertyNo),
Max(E.InstallationPlace),
Max(E.InstallationDate),
Max(E.BuyDate),
Max(Vt.TypeCaption),
Max(E.VisitChosen),
Max(E.LastVisitDate),
Max(V.VisitReport)
FROM 
TblEquipment E 
LEFT JOIN 
TblVisitType Vt 
on
 E.VisitType=Vt.VisitTypeId 
LEFT JOIN 
TblVisit V 
on 
E.EquipmentId=V.EquipmentId 
WHERE 1=1 AND E.Deleted <> 'True'
Group BY E.Name`