SQL Server-选择多列按1列分​​组

时间:2019-06-07 09:29:50

标签: sql sql-server group-by

我看了很多选择许多列的示例,但仅按1列分组,我的似乎给了我重复的结果。参见下文,我想选择表中的所有列,但只想GROUP BY VehicleId。在屏幕截图上,您会看到结果实际上并未按VehicleId分组。

关于我在做什么错的任何想法吗?

尝试1:

SELECT 
    h.*,

    TotalFines = 1,
    TotalIncidents = 1,
    TotalVehicleAllocations = 1,
    TotalVehicleConditions = 1,
    TotalMileageApplications = 1
FROM
(
    SELECT h1.VehicleId FROM [dbo].[VehicleHistory] h1 GROUP BY h1.VehicleId
) GroupedList
INNER JOIN [dbo].[VehicleHistory] h ON GroupedList.VehicleId=h.VehicleId
ORDER BY
    h.VehicleId;

尝试2:

SELECT t1.* FROM VehicleHistory t1
INNER JOIN
(
    SELECT VehicleId FROM VehicleHistory GROUP BY VehicleId
)   t2
ON t1.VehicleId=t2.VehicleId

两个查询都产生相同的结果,每个VehicleId重复行,如下所示:

enter image description here

以下是我的预期结果。结果是由实体框架产生的查询。但是我想将linq查询重写为T-SQL:

enter image description here

1 个答案:

答案 0 :(得分:1)

这是因为您正在子查询中(与SELECT DISTINCT h1.VehicleId FROM [dbo].[VehicleHistory] h1相同)

SELECT h1.VehicleId FROM [dbo].[VehicleHistory] h1 GROUP BY h1.VehicleId

然后您要加入该列,这可能导致出现重复(VehicleHistory中有重复的ID)。

您需要做的是:

SELECT VehicleId,
       MAX(DateUpdated) DateUpdated, --or other aggregate function
       --rest of your columns in appropriate aggreagte functions
FROM VehicleHistory
GROUP BY VehicleId