多个查询到一个查询

时间:2015-11-05 00:26:19

标签: mysql sql subquery

我正在尝试将多个查询合并为一个。有人有什么想法吗?

SELECT In_year,count(In_year)AS Num_Of_Year 来自INTERNSHIP GROUP BY In_year;

SELECT In_qtr,count(In_qtr)AS Num_Of_Qtr 来自INTERNSHIP GROUP BY In_Qtr;

SELECT In_location,count(In_location)AS Num_Of_Location 来自INTERNSHIP GROUP BY In_location;

如果我自己运行每个查询,我会在结果中得到我想要的内容。我的问题是我无法弄清楚如何将这3个查询组合成1,我试图梳理它们,但最终得到了错误的输出。谢谢!

2 个答案:

答案 0 :(得分:1)

也许UNION子句和组织它可以做到这一点:

SELECT 'Year' As Topic, In_year As Value, count(In_year) AS Count 
FROM INTERNSHIP 
GROUP BY In_year

UNION ALL

SELECT 'Qtr' As Topic, In_qtr As Value, count(In_qtr) AS Count 
FROM INTERNSHIP 
GROUP BY In_Qtr

UNION ALL

SELECT 'Location' As Topic, In_location As Value, count(In_location) AS Count
FROM INTERNSHIP 
GROUP BY In_location;

这是在单个查询中显示它的唯一方法,因为三个SELECT将具有不同的行数,因此您无法以自然形式添加列。

答案 1 :(得分:0)

我们可以使用INTERNSHIP表作为驱动列表来连接其他“group by”SQL:

select
   t1.In_year, y.Num_Of_Year,
   t1.In_qtr, q.Num_Of_Qtr,
   t1.In_location, l.Num_Of_Location
FROM
  (select distinct In_year, In_qtr, In_location from INTERNSHIP)  t1
   join (SELECT In_year, count(In_year) AS Num_Of_Year FROM INTERNSHIP GROUP BY In_year) y on t1.In_year = y.In_year
   join (SELECT In_qtr, count(In_qtr) AS Num_Of_Qtr FROM INTERNSHIP GROUP BY In_Qtr) q on t1.In_Qtr = q.In_Qtr
   join (SELECT In_location, count(In_location) AS Num_Of_Location FROM INTERNSHIP GROUP BY In_location) l on t1.In_location = l.In_location