简体   繁体   中英

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.

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:

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. If I add eextra LEFT JOINs I get duplication of the rows and the counts are overstated.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM