2015-11-05 103 views
0

我正在嘗試將多個查詢合併爲一個查詢。有人有主意嗎?將多個查詢合併爲一個查詢

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

SELECT In_qtr,計數(In_qtr)AS Num_Of_Qtr FROM INTERNSHIP GROUP BY In_Qtr;

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

如果我自己運行這些查詢中的每一個,我就會得到我在查找的結果。我的問題是我無法弄清楚如何將這3個查詢合併爲1,我試圖梳理它們,但最終得到錯誤的輸出。謝謝!

回答

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都會有不同的行數,所以你不能添加自然形式的柱子。

+0

謝謝!我明白你的答案是最好的。 – mpeytonfan18

0

我們可以用實習表作爲驅動表「按組」 SQLS其他連接:

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