我有两张桌子,例如"Locations"
和"Connections"
"Locations"
有价值观
Id | Dimension
---------------
1 | 4
2 | 8
3 | 2
"Connections"
维护属性
Origin | Destination | Value | Distance_KM
-------------------------------------------
1 | 2 | 500 | 30
1 | 3 | 100 | 20
2 | 1 | 100 | 10
2 | 3 | 300 | 10
3 | 1 | 100 | 40
我想使用以下属性表创建输出。相应"In"
地对应于"Destination"
from"Connections"
和"Out"
to "Origin"
。
Id | Dimension | In_Value | In_Count | In_Dist | Out_Value | Out_Count | Out_Dist
----------------------------------------------------------------------------------
1 | 4 | 200 | 2 | 50 | 600 | 2 | 50
2 | 8 | 500 | 1 | 30 | 400 | 2 | 20
3 | 2 | 400 | 2 | 30 | 100 | 1 | 40
我可以用两个查询分别达到我争取的结果。
查询 1
SELECT C.Destination, SUM(C.Value) AS In_Value, COUNT(C.Destination) AS In_Count, SUM(C.Distance_KM) AS In_Dist
FROM Connections AS C
GROUP BY C.Destination
查询 2
SELECT C.Origin, SUM(C.Value) AS Out_Value, COUNT(C.Origin) AS Out_Count, SUM(C.Origine_KM) AS Out_Dist
FROM Connections AS C
GROUP BY C.Origin
尽管如此,应该只有一个查询可以解决我的问题,不是吗?我试过了但没有成功。
SELECT L.Id AS Id, L.Dimension AS Dimension, C.In_Value, C.In_Count, C.In_Dist, C.Out_Value, C.Out_Count, C.Out_Dist
FROM Locations AS L
LEFT JOIN (
SELECT C.Destination,
SUM(C.Value) AS In_Value,
COUNT(C.Destination) AS In_Count,
SUM(C.Distance_KM) AS In_Dist
FROM Connections AS C
GROUP BY C.Destination
) ON L.Id = C.Destination
LEFT JOIN (
SELECT C.Origin,
SUM(C.Value) AS Out_Value,
COUNT(C.Origin) AS Out_Count,
SUM(C.Origine_KM) AS Out_Dist
FROM Connections AS C
GROUP BY C.Origin
) ON L.Id = C.Origin
基本上,我不知道我是否有资格在LEFT JOIN ON
已经存在的查询中添加第二个,对LEFT JOIN ON
吗?
参考:
小提琴
另一种可能性是连接
Connections
到Locations
onLocations.Id IN (Connections.Origin, Connections.Destination)
并根据匹配的两列中的哪一列执行一系列条件聚合。这就是我的想法:
注意:计数 (
In_Count
,Out_Count
) 已使用SUM
函数实现,这只是为了与其余代码保持一致。您可以改用COUNT
s,它看起来几乎相同,只是没有ELSE 0
位:尽管看起来可以说更简单,但这种方法不一定更快,尤其是在较大的数据集上。但是,如果性能不是问题,此选项可能看起来更具可读性,因此更易于维护。
该解决方案可以在这个小提琴的帮助下在线测试(借用 Akina 的小提琴的测试设置)。