我将尝试从SQL Server数据库中的数据制作图形。我会在所有街道上都看到这条街上生活的用户数,即使计数为零。
为此,我尝试了以下查询:
Create table Streets(
ID int IDENTITY primary key,
Name varchar(100)
);
create table users(
ID int IDENTITY primary key,
Username varchar(100),
StreetID int references Streets(id)
);
insert into streets values ('1st street'), ('2nd street'), ('3rd street'),
('4th street'), ('5th street');
insert into users values ('Pol', 1), ('Doortje', 1), ('Marc', 2), ('Bieke', 2),
('Paulien', 2), ('Fernand', 2), ('Pascal', 2), ('Boma', 3),
('Goedele', 3), ('Xavier', 4);
select s.name as street, count(s.name) as count
from users u inner join streets s on u.streetid = s.id
group by s.name
它给了我这个输出:
| | street | count |
| - | ---------- | ----- |
| 1 | 1st street | 2 |
| 2 | 2nd street | 5 |
| 3 | 3rd street | 2 |
| 4 | 4th street | 1 |
问题在于没有用户居住的第五街不会出现在结果中。我可以使用SQL Server执行此操作吗?在这里,你有一个小提琴
更新:如果这样做right join
,我将得到以下结果:
| | street | count |
| - | ---------- | ----- |
| 1 | 1st street | 2 |
| 2 | 2nd street | 5 |
| 3 | 3rd street | 2 |
| 4 | 4th street | 1 |
| 5 | 5th street | 1 |
因为
—
SqlWorldWide
right join
和right outer join
是一样的东西。我确实在我的答案中添加了@ jpmc26建议的解释。
COUNT(u.streetid)