SQL subquery (count distinct) - Any Ideas?

Поиск
Список
Период
Сортировка
От Matt Fulford
Тема SQL subquery (count distinct) - Any Ideas?
Дата
Msg-id Wzmdnb1DKJVDy8DfSa8jmA@karoo.co.uk
обсуждение исходный текст
Ответы Re: SQL subquery (count distinct) - Any Ideas?  (Rod Taylor <pg@rbt.ca>)
Список pgsql-sql
I'm trying to write a query to return the number of different customers 
called on a single day.  The database has a table called 'user', a table 
called 'caller_session' which references a 'user' record, and a table called 
'call' which references a 'caller_session'.  This is my current attempt:

select
user.name,
sum((select count(distinct call.customer_id) from call where 
call.caller_session_id=cs.caller_session_id)) as contacted
from user, caller_session cs
where cs.user_id=user.user_id
and date(cs.session_date) = date('2005-04-13')
group by user.name;

I get back a list of names and a call count (as desired), but the count is 
not correct!  The subqery is counting the number of different customers 
called for each caller_session, and summing them based on the user.name 
field.  If the same customer is called in 2 different sessions, this is 
being counted as 2 customers, but should be 1!

The 'contacted' count calculation has to be in a subquery as above, because 
there are other subqueries after this one to calculate other data based on 
the outer query (the outer query has to be as it is here).  Not quite sure 
where the sum, count and distinct should really go to get the required 
results!

Any help greatly appreciated!





В списке pgsql-sql по дате отправления:

Предыдущее
От: "Bill Lawrence"
Дата:
Сообщение: Re: Getting the output of a function used in a where clause
Следующее
От: Kai Hessing
Дата:
Сообщение: can a function return a virtual table?