如何返回Null意味着零的数据?

时间:2013-04-24 19:29:52

标签: sql null counting

我有一个表格,显示某些数据点的文本中出现的单词数。这是一个简化的例子:

Word   Chapter   Count
dog    1         3
dog    2         7
dog    3         1
cat    2         4

请注意,第1章和第3章中没有'cat'行,因为那里没有使用该词。

我需要SELECT INTO临时表(准备其他聚合等)上面的数据,但是我需要'cat'来显示第1章和第3章,计数为0.结果应该是:

Word   Chapter   Count
dog    1         3
dog    2         7
dog    3         1
cat    1         0
cat    2         4
cat    3         0

任何提示都会非常感激。 感谢。

4 个答案:

答案 0 :(得分:3)

我不知道您的数据结构,但我认为您要做的是:

create table Chapters (Chapter int);
insert Chapters values (1);
insert Chapters values (2);
insert Chapters values (3);

create table Words (Word varchar(50));
insert into Words values ('dog');
insert into Words values ('cat');

create table Chapters_Words (Word varchar(50), Chapter int, [Count] int);
insert into Chapters_Words values ('dog', 1, 3);
insert into Chapters_Words values ('dog', 2, 7);
insert into Chapters_Words values ('dog', 3, 1);
insert into Chapters_Words values ('cat', 2, 4);

select
    f.Word, 
    f.Chapter, 
    isnull(w.[Count], 0) [Count]
from
    Chapters_Words w
    right join (
        select w.Word, c.Chapter
        from Chapters c
        cross join Words w
    ) f on f.Chapter = w.Chapter and f.Word = w.Word

结果:

Word                                               Chapter     Count
-------------------------------------------------- ----------- -----------
dog                                                1           3
dog                                                2           7
dog                                                3           1
cat                                                1           0
cat                                                2           4
cat                                                3           0

答案 1 :(得分:1)

Null NOT 表示零,“零”也不表示空。

唉...

话虽如此,“coalesce()”函数是Pop Favorite,具体取决于您的RDBMS实现:COALESCE with NULL

另见SQL ISNULL(), NVL(), IFNULL() and COALESCE() Functions

答案 2 :(得分:0)

我相信你需要COALESCE

COALESCE(Count, 0) 

完整示例:

SELECT Word, Chapter, COALESCE(Count, 0)
FROM YourTable

答案 3 :(得分:0)

取决于你在做什么?如果行正在退出,则可以使用外部联接。在Oracle中,您可以使用nvl()将null更改为其他内容。例如,总和为零。