2016-11-11 129 views
0

我試圖讓每個教室的學生人數在場。Union MYSQL中的GROUP BY

的條件是:

  1. 從教室裏所有的學生其中ClassroomID是< 99和具有(DropTime <> '00:00' 和PickupTime = '00:00' )和日期是20161111

  2. 從教室裏所有的學生都在那裏ClassroomId> 99,並有(DropTime = '00:00' )和日期是20161111

我使用日E採用在MySQL查詢並能正常工作,我得到正確的結果:

SELECT 
    COUNT(a.Id) AS total, c.Name 
FROM 
    Attendance a 
INNER JOIN 
    Classroom c ON a.classroom = c.Id 
WHERE 
    DropDate = '20161111' 
AND DropTime <> '00:00' 
AND PickupTime = '00:00' 
GROUP BY Name 

不同之處在於,當我嘗試做一個工會獲得另外一間教室的結果(即ClassroomID> 99),它並沒有帶來各教室,只帶1個教室。 這是我正在使用的聯合查詢;

SELECT 
SUM(total), Name 
FROM 
(SELECT 
    COUNT(a.Id) AS total, c.Name 
FROM 
    Attendance a 
INNER JOIN Classroom c ON a.classroom = c.Id 
WHERE 
    DropDate = '20161111' 
     AND DropTime <> '00:00' 
     AND PickupTime = '00:00' 
     AND c.Id < 99 
UNION ALL 
    SELECT 
    COUNT(a.Id) AS total, c.Name 
FROM 
    Attendance a 
INNER JOIN Classroom c ON a.classroom = c.Id 
WHERE 
    DropDate = '20161111' 
     AND PickupTime = '00:00' 
     AND c.Id > 99) t 
GROUP BY Name 

回答

1

集團通過的必須到位針對每個聚集。因此你需要三個一組的; 1爲每個聯合聲明,因爲兩者都是聚合的,以及一個用於外部選擇...因爲你也在聚合。

換句話說,每個查詢必須能夠在它自己可以在另一個操作之前自己操作。你的兩個內聯查詢在大多數RDBMS系統中都會失敗,因爲缺少group by,但是MYSQL的擴展組使這個變複雜。

但是,可能有一種更有效的方式來編寫查詢......但這是一個基於您的初始嘗試的工作版本。

SELECT 
SUM(total), Name 
FROM 
(SELECT 
    COUNT(a.Id) AS total, c.Name 
FROM 
    Attendance a 
INNER JOIN Classroom c ON a.classroom = c.Id 
WHERE 
    DropDate = '20161111' 
     AND DropTime <> '00:00' 
     AND PickupTime = '00:00' 
     AND c.Id < 99 
GROUP BY c.name 
UNION ALL 
    SELECT 
    COUNT(a.Id) AS total, c.Name 
FROM 
    Attendance a 
INNER JOIN Classroom c ON a.classroom = c.Id 
WHERE 
    DropDate = '20161111' 
     AND PickupTime = '00:00' 
     AND c.Id > 99 
GROUP BY c.name) t 
GROUP BY t.name 

這似乎是simplier和應該達到相同的結果(只要我沒有螺絲的東西了),它應該是,因爲它沒有產生3個不同的組,然後將它們結合起來更快。

SELECT COUNT(a.Id) AS total 
    , c.Name 
FROM Attendance a 
INNER JOIN Classroom c 
    ON a.classroom = c.Id 
WHERE DropDate = '20161111' 
    AND ((DropTime <> '00:00' AND PickupTime = '00:00' AND c.Id < 99) 
    OR (PickupTime = '00:00' AND c.Id > 99)) 
GROUP BY c.name 
+0

完美謝謝! – snowflakes74