2017-05-30 56 views
0

我有一個位置表,餐館表和賭場表,後兩個包括他們的位置的ID。計算兩個表中的位置實例,在結果中存儲兩列

從這些表格中我想要一個新的位置表,以及一列計算在該位置有多少餐館的列以及該位置有多少賭場,除非兩者都爲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 

回答

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 
+0

'GROUP BY l.location_id',而不是'GROUP BY l.id'一個錯字我敢肯定...... –

+0

燁..錯字感謝 – maSTAShuFu

+0

謝謝!雖然有一些問題。這似乎在任何地方都有餐館或賭場的情況下工作,但當它們都有時,它給我的數字要高得多,例如,當有真正的165家餐館和20家賭場的時候,餐廳和賭場都是3300,或者有186家餐館和26家賭場的4836家。它還包括結果地點與0餐廳和0賭場,我寧願沒有。 – raphaelrk