我有一张地点表,一张餐馆桌子和一张赌场桌子,后两张包括他们所在地的身份。
从这些表中我想要一个新的位置表,以及一个列数,计算该位置有多少家餐馆,以及该位置有多少家赌场,除非两者都有0,在这种情况下我要排除结果中的那个位置。
以下伪代码查询对我来说只对餐厅进行上述操作有效,但我在添加赌场时遇到了麻烦。有关如何实现这一目标的任何建议吗?
SELECT r.location_id, l.name, count(r.location_id) FROM restaurants r join locations l ON r.location_id = l.id GROUP BY l.id, l.name;
这是我所拥有的表格的示例数据
Locations
id | name | lat_lng
----+---------+-----------
1 | Florida | 3A29F3840
2 | Nevada | 4G32J1273
3 | Maine | 9Y35V9241
Restaurants
id | location_id | name
----+-------------+--------------------
1 | 2 | McDonalds
2 | 1 | Cheesecake Factory
3 | 2 | Steak and Shake
Casinos
id | location_id | name
----+-------------+-----------------
1 | 2 | Ballys
2 | 2 | Treasure Island
我希望得到的表格的一个例子
Result
location_id | location_name | restaurant_count | casino_count
------------+---------------+------------------+--------------
1 | Florida | 1 | 0
2 | Nevada | 2 | 2
答案 0 :(得分:1)
左连接和分组依据,计数明显..锚定位置
SELECT l.id [Location Id],
l.name [Location Name],
count(distinct r.id) [Location count],
count(distinct c.id) [Casino Count]
FROM locations l
left join restaurants r ON r.location_id = l.id
left join casinos c on c.location_id = l.id
GROUP BY l.id,l.name
having count(distinct r.id)> 0 or
count(distinct c.id) > 0
/* sample script using SQL-SERVER */
select *
into #Locations
from (
values( 1, 'Florida', '3A29F3840'),
(2,'Nevada','4G32J1273'),
(3,'Maine','9Y35V9241')
)
as x (id,name,lat_lng)
select *
into #Restaurants
from (
values( 1,2),
(2,1),
(3,2)
)
as x (id,location_id)
select *
into #Casinos
from (
values( 1,2),
(2,2)
)
as x (id,location_id)
SELECT l.id [Location Id],
l.name [Location Name],
count(distinct r.id) [Location count],
count(distinct c.id) [Casino Count]
FROM #locations l
left join #restaurants r ON r.location_id = l.id
left join #casinos c on c.location_id = l.id
GROUP BY l.id,l.name
having count(distinct r.id)> 0 or
count(distinct c.id) > 0
drop table #Locations
drop table #Restaurants
drop table #Casinos
结果
Location Id Location Name Location count Casino Count
----------- ------------- -------------- ------------
1 Florida 1 0
3 Maine 0 0
2 Nevada 2 2