2017-07-26 49 views
1

我想在這裏挑戰SQL社區。讓我們獲得以下數據和SQL查詢:SQL挑戰:爲什麼SQL查詢不組根據NULL

create table A 
(
    a_id integer unique, 
    code int 
); 

create table B 
(
    a_id integer foreign key references A(a_id), 
    b_count int 
); 

insert into A values (1, 20); 
insert into A values (3, 30); 
insert into A values (null, 30); 

insert into B values (1, 100); 
insert into B values (1, 120); 
insert into B values (null, 200); 

select A.a_id, sum(B.b_count) Bsum 
from A 
left join B on A.a_id = B.a_id 
group by A.a_id 

爲什麼SQL查詢沒有求和NULL的值?換句話說,我們爲什麼

a_id Bsum 
--------------- 
NULL NULL 
1  220 
3  NULL 

,而不是

a_id Bsum 
--------------- 
NULL 200 
1  220 
3  NULL 
+0

[文章](https://technet.microsoft.com/en-us/library/ms191504(V = SQL.105)的.aspx)約'NULL'值。這應該可以幫助你理解爲什麼不分組。 – Rokuto

+0

將A.a_id = B.a_id中的左連接B更改爲on子句中的isnull(A.a_id,-1)= isnull(B.a_id,-1),以及SELECT中的nulliff(A.a_id,-1)你會得到它。在NULL上不能等於或不等於另一個NULL,即。 – sepupic

+1

挑戰:你認爲結果如下查詢:'select case when null = null then'sure'else'nope'end as does_null_equal_null' – LukStorms

回答

5

這有什麼好做的sum()。究其原因是比較NULL工作的left join和方式。這是您的查詢:

select A.a_id, sum(B.b_count) Bsum 
from A left join 
    B 
    on A.a_id = B.a_id 
group by A.a_id; 

在哪裏a_idNULL行中,=計算結果爲NULL - 這是不正確的。你似乎要的是:

select A.a_id, sum(B.b_count) Bsum 
from A left join 
    B 
    on A.a_id = B.a_id or (A.a_id is null and B.a_id is null) 
group by A.a_id; 
+0

再次,你在哪裏比我快.... :-) –

+0

好吧,這似乎不是一個挑戰。我嘗試了一個令人誤解的標題,但它沒有工作:) –