简体   繁体   English

SQL中的联合与聚合

[英]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? 我有3个SQL查询,我想使用Union将它们合并到一个表中,但尝试了不同的查询,但没有一个起作用,我缺少什么?

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. 因此,最终的输出将是方案(类型,位置,mcd,县),其中类型包含来自3个表的类型的所有不同值,并且位置包含类型值出现在位置表中的次数与mcs和county相同。

You'd need an outer query to get the type values from the three queries combined. 您需要一个外部查询才能从三个查询的组合中获取type值。

Here's an example, using the UNION ALL set operator to combine the results of the three queries. 这是一个示例,使用UNION ALL集合运算符组合三个查询的结果。 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. 该查询是一个内联视图,由外部查询引用,该外部查询在type列上执行GROUP BY,在COUNT / 0列上进行SUM聚合。

  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. 通过每个查询中的GROUP BY子句,不需要DISTINCT关键字。

It seems join 3 table together would be more suitable for your requirement. 看来将3表连接在一起会更适合您的要求。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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