Bako Gdaniec
Bako Gdaniec

Reputation: 49

Compare two columns from two tables and return SUM of matches

I am working on a project where I have to compare two tables together and sum the number of occurrences. For this example I will use name as the key that I would like to compare. I have used Union all and Count(*) but it wouldn't give me the desired output.

Table apple

+----+-------+---------+
| Id | Name  | Surname |
+----+-------+---------+
|  1 | Adam  | Jaxon   |
|  2 | Adam  | Brixton |
|  3 | Brian | Simpson |
|  4 | Adam  | Steper  |
|  5 | Brian | Bastion |
+----+-------+---------+

Table orange

+----+-------+---------+
| id | name  | surname |
+----+-------+---------+
|  1 | Adam  | Thompson|
|  2 | Brian | Coach   |
|  3 | Jhon  | Sinded  |
+----+-------+---------+

There is one name match for Adam and one match for Brian so the desired output I would like to receive is

+-------+
| Total |
+-------+
|  3    |
|  1    |
+--------+

The query that I am using similar to the person who had answered the question however there are few changes. Unfortunately this only returns number of matches for each name

SELECT COUNT(*)
FROM
(
SELECT Name
FROM 
apple
UNION ALL
SELECT 
NAME
FROM
orange
) as named
GROUP BY name



+----------+
| Count(*) |
+----------+
|   2    
|   3
+----------+

Upvotes: 0

Views: 498

Answers (2)

Gustavo S. Rodrigues
Gustavo S. Rodrigues

Reputation: 187

Try it, grouping and count name:

SELECT 
    id,
    name,
    surname
    count(1) as total
    FROM
    (
        SELECT 
            id,
            name,
            surname
            FROM apple
        UNION ALL
        SELECT 
            id,
            name,
            surname
        FROM orange
    )
GROUP BY name

UPDATE

To SUM all results before your query:

SELECT sum(total) 
FROM (
        SELECT 
            id,
            name,
            surname
            count(1) as total
            FROM
            (
                SELECT 
                    id,
                    name,
                    surname
                    FROM apple
                UNION ALL
                SELECT 
                    id,
                    name,
                    surname
                FROM orange
            )
    GROUP BY name
)

Upvotes: 1

Aconcagua
Aconcagua

Reputation: 25536

No DB server available, so haven't tested it - should do the trick, however:

SELECT COUNT(*) FROM
(
    SELECT DISTINCT apple.name FROM apple
        JOIN orange ON apple.name = orange.name
);

Upvotes: 0

Related Questions