Rayan
Rayan

Reputation: 65

Union and Aggregation in SQL

I have 3 SQL queries I want to combine them in one table using Union I tried different queries but none of them worked, What am I missing?

SELECT DISTINCT 
       place.type AS type, 
       COUNT(place.type)AS place,
       0 AS msd,
       0 AS county
FROM   place 
GROUP BY place.type;

SELECT DISTINCT 
       mcd.type, 
       0 AS place, 
       COUNT(mcd.type) AS msd, 
       0 AS county
FROM   mcd 
GROUP BY mcd.type;

SELECT DISTINCT 
       county.type, 
       0 AS place, 
       0 AS msd,
       COUNT(county.type) AS county
FROM   county 
GROUP BY county.type;

So the final output would be the scheme (type,place,mcd,county) where type contains all different values for types from the 3 tables and place contains the number times the value of type appears in place table and the same for mcs and county.

Upvotes: 1

Views: 2182

Answers (2)

Jaugar Chang
Jaugar Chang

Reputation: 3196

It seems join 3 table together would be more suitable for your requirement.

SELECT coalese(place.type,mcd.type,conty.type) AS type, 
       COUNT(place.type)AS place,
       COUNT(mcd.type) AS msd, 
       COUNT(county.type) AS county
FROM   place 
FULL OUTER JOIN   mcd    ON place.type = mcd.type
FULL OUTER JOIN   county ON place.type = county.type 
GROUP BY coalese(place.type,mcd.type,conty.type)

Upvotes: 0

spencer7593
spencer7593

Reputation: 108530

You'd need an outer query to get the type values from the three queries combined.

Here's an example, using the UNION ALL set operator to combine the results of the three queries. That query is an inline view, referenced by an outer query that does a GROUP BY on the type column, and SUM aggregate on the COUNT/0 columns.

  SELECT t.type
       , SUM(t.place)
       , SUM(t.msd)
       , SUM(t.county)
    FROM ( SELECT place.type AS type
                , COUNT(place.type) AS place
                , 0 AS msd
                , 0 AS county
             FROM place
            GROUP BY place.type
            UNION ALL
           SELECT mcd.type
                , 0 AS place
                , COUNT(mcd.type) AS msd
                , 0 AS county
             FROM mcd
            GROUP BY mcd.type
            UNION ALL
           SELECT county.type
                , 0 AS place
                , 0 AS msd
                , COUNT(county.type) AS county
             FROM county
            GROUP BY county.type
         ) t
     GROUP BY t.type

With the GROUP BY clause in each query, the DISTINCT keyword isn't needed.

Upvotes: 2

Related Questions