2014-08-28 2 views
2

я пытаюсь присоединиться к 3 таблицы, как это:Регистрация 3 таблицы с SQL запросов

таблица 1: страна

Id | Country 
------------------- 
1 | UK 
2 | USA 
3 | France 

Таблица 2: Даты

Id  | Date 
----------------- 
20000101 | 2000-01-01 
20000102 | 2000-01-02 
... 
20140901 | 2014-09-01 

таблица 3: Клиент

Id | Customer | Date_Creation_Id | Country_Id 
--------------------------------------------- 
1  | AAA  | 20000102   | 1 
2  | B   | 20000102   | 2 
2  | CC   | 20000103   | 2 

Я хочу найти ну mber нового клиента для всей даты и всей страны.

Date  | Country | number of creation 
------------------------------------------------- 
20000101 | UK  | 0 
20000101 | USA  | 0 
20000101 | France | 0 

20000102 | UK  | 1 
20000102 | USA  | 2 
20000102 | France | 0 

20000103 | UK  | 0 
20000103 | USA  | 1 
20000103 | France | 0 

Я пытаюсь с этим запросом

select count(*) as count,Customer.Date_Creation_Id, Customer.Country_Id 
from customer 
Right join Date on Dates.Id = Customer.Date_Creation_Id 
Right join Country on Country.Id = Customer.Country_Id 
group by Customer.Date_Creation_Id, Customer.Country_Id 

Но я не все даты с ней

ответ

1
SELECT  D.Id,C.Country,COUNT(CU.Id) [number of creation] 
FROM  Country C CROSS JOIN [Date] D 
LEFT JOIN customer CU on D.Dates.Id = CU.Date_Creation_Id And C.Country.Id = CU.Country_Id 
GROUP BY D.Id,C.Country 
ORDER BY D.Id,C.Id 
4

Вам нужно создать список всех стран и дат первых, с помощью cross join и то left join ваши данные:

select d.id as date_id, c.id as country_id, count(cu.id) as cnt 
from dates d cross join 
    country c left join 
    customers cu 
    on cu.date_creation_id = d.id and cu.country_id = c.id 
group by d.id, c.id 
order by d.id, c.id; 
1

Проблема с запросом, что вы группировать по столбцам, которые могут быть нулевым после right join (Customer.Date_Creation_Id, Customer.Country_Id)

Решение использовать столбцы из ваших размеров Country и Dates

select count(*) as count, Dates.Id Date_Creation_Id, Country.Id Country_Id 
from customer 
Right join Date on Dates.Id = Customer.Date_Creation_Id 
Right join Country on Country.Id = Customer.Country_Id 
group by Dates.Id, Country.Id 
Смежные вопросы