简体   繁体   中英

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.

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.

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)

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