[英]Summarising multiple vectors on a single SQL table using GROUP UNION and SUM
I'm trying to create a query that returns counts by relationship type for all entities in a table.我正在尝试创建一个查询,该查询按关系类型返回表中所有实体的计数。 eg.例如。
1|VenueName1|0|0|0|
where 0,0,0 is the counts for the number of relationships found.其中 0,0,0 是找到的关系数的计数。
The table itself contains a number of external relationships to many different external item types.该表本身包含许多与许多不同外部项目类型的外部关系。 Each association can appear in a 'forward' or 'backward' manner in the table, so for example, each relationship can appear one of two ways:每个关联都可以在表中以“向前”或“向后”的方式出现,例如,每个关系可以出现以下两种方式之一:
|objectTypeId|objectId|associatedId |associatedTypeId|
| 13 | 1 | 8 | 2 |
| 2 | 8 | 1 | 13 |
Makes sense?说得通? They will normally only appear once, but could be in either 'direction'.它们通常只会出现一次,但可以在任一“方向”。 As such, to get the total relationships for a given type, I use a UNION similar to:因此,为了获得给定类型的总关系,我使用类似于以下的 UNION:
SELECT ip.id, ip.name, SUM(totalUnion.EventTotals) as Events
FROM iplace ip
LEFT JOIN
(
SELECT object_id, count(*) as EventTotals FROM `iassociation` ia
WHERE object_type_id=2 AND associated_object_type_id=14
GROUP BY object_id
UNION ALL
SELECT associated_object_id, count(*) as EventTotals FROM `iassociation` ia
WHERE associated_object_type_id=2 AND object_type_id=14
GROUP BY associated_object_id
) totalUnion ON ip.id = totalUnion.object_id
WHERE ip.type_id IN (4,7,11,15,16)
GROUP BY ip.id
That works ok.. My problem is that I want to do the same for another 2 typeIds, giving two more SUM()s to show different relationship type totals against the one entity.没问题。我的问题是我想对另外 2 个 typeId 做同样的事情,再给两个 SUM() 来显示针对一个实体的不同关系类型总计。 If I add eextra LEFT JOINs I get duplication of the rows and the counts are overstated.如果我添加 eextra LEFT JOIN,我会得到重复的行并且计数被夸大了。
Hope that makes some sense.希望这有点道理。 Can anyone suggest a solution?任何人都可以提出解决方案吗?
For your subquery you can do something like this:对于您的子查询,您可以执行以下操作:
SELECT
object_id,
SUM(CASE WHEN object_type_id = 2 AND associated_object_type = 14 THEN 1 ELSE 0 END) AS event_1,
SUM(CASE WHEN object_type_id = 5 AND associated_object_type = 8 THEN 1 ELSE 0 END) AS event_2
FROM
iassociation
UNION ALL
GROUP BY
object_id
SELECT
associated_object_id,
SUM(CASE WHEN associated_object_type = 2 AND object_type_id = 14 THEN 1 ELSE 0 END) AS event_1,
SUM(CASE WHEN associated_object_type = 5 AND object_type_id = 8 THEN 1 ELSE 0 END) AS event_2
FROM
iassociation
GROUP BY
associated_object_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.