MsSql Group By两次

时间:2015-12-10 16:13:43

标签: sql sql-server group-by

examle table

我有3张桌子:

Corridors (CorridorID int Primary)
Locations(LocationID int Primary, LocationMax int, CorridorID int)
Inventory(Inventory ID, SerialNo varchar)

我尝试了这样的查询:

select C.ID, Count(Distinct(SerialNo)), Sum(L.Max) as TotalCapacity from Corridors as C
Inner Join Locations L on L.CorridorID=C.ID
Inner Join Inventory I on I.LocationID=L.ID
Group By C.ID

但是Sum多次获取LocationMax

对我而言,真正的结果是(30 + 40 + 10 + 20)我的意思是每个地点的一次总和。 有可能两次做“Group By”吗?我怎样才能得到这样的结果? (30 + 40 + 10 + 20)

1 个答案:

答案 0 :(得分:0)

像@TIM建议使用MAX ...试试这个。 解释 步骤1首先按照您之后的关键列值对其进行分区...(您也可以根据您的要求使用Max,min等。)&找到重复的。

步骤2:将放置外部查询并根据组进行总结。使用where子句

过滤任何可能的重复项

for.e.g

 SELECT 
    SUM(LocationMax)AS Kapasite
    ,ID
FROM 
(
    SELECT ROW_NUMBER() OVER (PARTITION BY C.ID Order by C.ID ) as Row_no,
    C.ID,
    L.LocationMax
    FROM Corridors as C
        INNER JOIN Locations L ON L.CorridorID=C.ID
        INNER JOIN Inventory I ON I.LocationID=L.ID
)T
WHERE T.Row_no=1
Group by ID