可以使用顶点和边表来表示图。
Vertex保存节点详细信息,edge保持关系。
VERTEX EDGE
------ ----------------------------
ID ID | Source | Target
------ ----------------------------
A 1 A B
B 2 A B
C 3 B C
D 4 B D
E 5 D B
6 A D
7 B A
8 E A
图表:
我试图使用SQL查询获得每个节点的直接邻居。
OUTPUT
---------------------------
ID | COUNT
---------------------------
A 3
B 3
C 1
D 2
E 1
说明:
A与E,D,B有连接
B连接到C,A,D
答案 0 :(得分:1)
要添加此变体:
select source, count(distinct target)
from
(select source, target
from edge e_out
union all
select target, source -- note the switch of src/trgt columns
from edge e_in)
group by source
order by source;
答案 1 :(得分:1)
请检查以下SQL查询,提供您要查找的确切结果
select
Vertex.ID,
Count(Neighbour) as "Count"
from GraphVertex as Vertex
left join (
select
v.ID,
e.Target as Neighbour
from GraphVertex as v
inner join GraphEdge as e
on v.ID = e.Source
union
select
v.ID,
e.Source as Neighbour
from GraphVertex as v
inner join GraphEdge as e
on v.ID = e.Target
) as Neighbours
on Vertex.ID = Neighbours.ID
group by Vertex.ID
order by Vertex.ID;
答案 2 :(得分:1)
虽然您已将表命名为Vertex和Edge,但此处提供的所有解决方案似乎都是SQLScript解决方案,而不是图形语言解决方案。
我尝试为您的请求创建一个Graph数据库解决方案,但我遇到了一些必须克服的困难。
首先,因为我是Graph的新手,所以找不到直接的解决方案。你知道Edge是有针对性的记录。但是你的问题想要两个方向的邻居总数。所以我不得不通过交叉更改源列和目标列来对行进行公开。
然后我使用了以下程序
CREATE PROCEDURE graphProcedureSample2(in ID varchar(2), out cnt int)
LANGUAGE GRAPH READS SQL DATA AS
BEGIN
Graph g = Graph("A00077387", "SAMPLEGRAPHWORKSPACE");
cnt = 0;
Vertex v = Vertex(:g, :ID);
Multiset<Vertex> neighbors = NEIGHBORS (:g, :v, 1, 1);
Multiset<Edge> edges = EDGES (:g, :v, :neighbors);
cnt = INT(COUNT(:neighbors));
END;
但上面的代码仅适用于单个顶点。
我必须create HANA database cursor并遍历所有顶点,然后为每个顶点调用此SP。
我已将结果存储在临时表中,并通过查询此临时表获得您请求的结果。
我希望它有所帮助,
答案 3 :(得分:0)
select a, count(*) as connections from
(
select a, b from
(
select Source a, Target b from EDGE
union
select Target a, Source b from EDGE
) group by a,b
) group by a
答案 4 :(得分:0)
您可以使用以下查询:
SELECT CASE WHEN Source < Target THEN Source ELSE Target END AS Node1,
CASE WHEN Source >= Target THEN Source ELSE Target END AS Node2
FROM EDGE
得到:
Node1 Node2
-------------
A B
A B
B C
B D
B D
A D
A B
A E
这是EDGE
表的简化版本,仅包含节点连接信息。
您可以使用DISTINCT
:
SELECT DISTINCT
CASE WHEN Source < Target THEN Source ELSE Target END AS Node1,
CASE WHEN Source >= Target THEN Source ELSE Target END AS Node2
FROM EDGE
以便删除重复项:
Node1 Node2
-------------
A B
A D
A E
B C
B D
现在,您可以将上述查询包装在CTE
中,取消忽略,然后计算:
;WITH SimpleEDGE AS (
SELECT DISTINCT
CASE WHEN Source < Target THEN Source ELSE Target END AS Node1,
CASE WHEN Source >= Target THEN Source ELSE Target END AS Node2
FROM EDGE
)
SELECT Node, COUNT(*) AS cnt
FROM (
SELECT Node1 AS Node
FROM SimpleEDGE
UNION ALL
SELECT Node2 AS Node
FROM SimpleEDGE
) AS t
GROUP BY Node
<强>输出:强>
Node cnt
-----------
A 3
B 3
C 1
D 2
E 1