Warm tip: This article is reproduced from serverfault.com, please click

neo4j-Cypher:Union中的相关变量

(neo4j - Cypher: Correlated variables in Union)

发布于 2020-12-01 22:31:58

我需要回答以下查询:基于商店销售量的前三名商店城市以及所有其他城市的商店销售量之和。

用以下查询

// Top 3 cities
MATCH (t:Store)<-[:HasStore]-(s:Sales)
WITH t.StoreCity AS StoreCity, t, sum(s.StoreSales) AS StoreSales
ORDER BY sum(s.StoreSales) DESC LIMIT 3
// All other cities
WITH StoreCity, StoreSales, collect(t) AS TopThreeCities
MATCH (t1:Store)<-[:HasStore]-(s:Sales)
WHERE NOT(t1 IN TopThreeCities)
// JOIN of the two results -> I would need the UNION
RETURN StoreCity, StoreSales, "Other cities" AS StoreCity1, sum(s.StoreSales) AS StoreSales1

我能够获得以下答案

"A" 10  "Other Cities"  50
"B" 9   "Other Cities"  50
"C" 8   "Other Cities"  50

但我想获得

"A" 10
"B" 9
"C" 8
"Other Cities"  50

知道如何获得这个吗?我尝试了许多可能性,但都没有成功:-(

Questioner
Esteban Zimanyi
Viewed
11
Marj 2020-12-03 02:23:28

使用UNION:

// Top 3 cities
MATCH (t:Store)<-[:HasStore]-(s:Sales)
RETURN t.StoreCity AS StoreCity, sum(s.StoreSales) AS StoreSales
ORDER BY sum(s.StoreSales) DESC LIMIT 3
// All other cities
UNION
MATCH (t:Store)<-[:HasStore]-(s:Sales)
WITH t.StoreCity, sum(s.StoreSales) AS AllStoreSales
ORDER BY AllStoreSales DESC SKIP 3
RETURN "Other cities" AS StoreCity, sum(AllStoreSales) AS StoreSales

UNION运行两个不同的查询,因此在UNION之前,我们找到了销售量最高的三个城市,并返回了它们的名称和计数,就像你最初使用的一样

在UNION之后,再次运行相同的基本查询以查找按城市,按降序排列的销售总额,然后跳过前三个结果。剩余城市的销售额相加并作为“其他城市”返回

UNION的两个部分是完全分开的,但是两个查询必须返回具有相同列名和相同列顺序的相同数量的列。