2013-04-05 225 views
1

我無法獲得業務代碼相同的註冊總和。我的代碼如下:集團和總和

SELECT DISTINCT lb.building_code , lb.bus_code, gl.building_name, gl.bus_name, SUM(gl.enrollment) AS enrollment 
    FROM table1 AS gl 
    RIGHT OUTER JOIN table 2 AS lb ON gl.building_key = lb.building_key 
    where gl.bus_name = 'Business' 
    and gl.year_cd = 2010 
    GROUP BY lb.building_code, lb.bus_code, gl.building_name, gl.bus_name, gl.enrollment 

電流輸出:

building_code bus_code bus_name  enrollment 
4581    0000  Business A 12 
4581    0000  Business A 13 
4581    0109  Business B 100 
4581    0109  Business B 120 
4581    0209  Business C 130 
4581    0402  Business D 35 

所需的輸出:

building_code bus_code bus_name  enrollment 
    4581    0000  Business A 25 
    4581    0109  Business B 220 
    4581    0209  Business C 130 
    4581    0402  Business D 35 
+0

對不起SQL服務器 – Tone 2013-04-05 17:09:54

+1

嘗試刪除入學率從您的集團聲明。 – zundarz 2013-04-05 17:13:34

+0

爲什麼你有'DISTINCT' *和*'GROUP BY'?當你在WHERE子句中過濾外部表時,爲什麼一個'RIGHT JOIN',無論如何都使它成爲'INNER JOIN'? – 2013-04-05 17:38:30

回答

1

GROUP BY條款刪除gl.building_name, gl.enrollment

SELECT 
    lb.building_code , 
    lb.bus_code, 
    gl.bus_name, 
    SUM(gl.enrollment) AS enrollment 
FROM table1 AS gl 
RIGHT OUTER JOIN table 2 AS lb ON gl.building_key = lb.building_key 
where gl.bus_name = 'Business' 
    and gl.year_cd = 2010 
GROUP BY lb.building_code, lb.bus_code, gl.bus_name; 
1
SELECT lb.building_code, 
     lb.bus_code, 
     gl.bus_name,  
     SUM(gl.enrollment) AS enrollment 
    FROM table1 AS gl 
    RIGHT OUTER JOIN table 2 AS lb ON gl.building_key = lb.building_key 
    where gl.bus_name = 'Business' 
    and gl.year_cd = 2010 
    GROUP BY lb.building_code, 
      lb.bus_code, 
      gl.bus_name 
0

我會考慮兩次重寫。一,如果你的意思是這是一個外連接(所以包括table2中不在table1中的行),改變順序,使其成爲左連接,將table1的where子句移入join子句,刪除distinct,並從組中刪除非分組列:

SELECT lb.building_code, lb.bus_code, gl.building_name, 
    gl.bus_name, SUM(gl.enrollment) AS enrollment 
FROM dbo.table2 AS lb 
LEFT OUTER JOIN dbo.table1 AS gl 
    ON gl.building_key = lb.building_key 
    AND gl.bus_name = 'Business' 
    AND gl.year_cd = 2010 
GROUP BY lb.building_code, lb.bus_code, gl.building_name, gl.bus_name; 

(對於絕大多數的人來說,LEFT JOINRIGHT JOIN直觀得多。)

如果你真的不希望從table2中有任何不在table1中的行,則不要將其寫爲外連接:

SELECT lb.building_code, lb.bus_code, gl.building_name, 
    gl.bus_name, SUM(gl.enrollment) AS enrollment 
FROM dbo.table2 AS lb 
INNER JOIN dbo.table1 AS gl 
    ON gl.building_key = lb.building_key 
WHERE gl.bus_name = 'Business' 
    AND gl.year_cd = 2010 
GROUP BY lb.building_code, lb.bus_code, gl.building_name, gl.bus_name; 
0

嘗試

由於您使用右外連接,所以不要忘記添加ISNULL在SUM聚合函數來處理從表中的數據不匹配2

SELECT lb.building_code , lb.bus_code, gl.bus_name, SUM(Isnull(gl.enrollment,0)) AS enrollment 
    FROM table1 AS gl 
    RIGHT OUTER JOIN table 2 AS lb ON gl.building_key = lb.building_key 
    where gl.bus_name = 'Business' 
    and gl.year_cd = 2010 
    GROUP BY lb.building_code , lb.bus_code, gl.bus_name