1

I am trying to formulate a query which, given two tables: (1) Salespersons, (2) Sales; displays the id, name, and sum of sales brought in by the salesperson. The issue is that I can get the id and sum of brought in money but I don't know how to add their names. Furthermore, my attempts omit the salespersons which did not sell anything, which is unfortunate.

In detail:

There are two naive tables:

create table Salespersons (
    id integer,
    name varchar(100)
);

create table Sales (
    sale_id integer,
    spsn_id integer,
    cstm_id integer, 
    paid_amt double
);

I want to make a query that for each Salesperson displays their total sum of sales brought in.

This query comes to mind:

select spsn_id, sum(paid_amt) from Sales group by spsn_id

This query only returns list of ids and total amount brought in, but not the names of the salespersons and it omits salespersons that sold nothing.

How can I make a query that for each salesperson in Salespersons table, prints their id, name, sum of their sales, 0 if they have sold nothing at all.

I appreciate any help!

Thanks ahead of time!

4

3 回答 3

3

尝试这个:

SELECT sp.id,sp.name,SUM(NVL(s.paid_amt,0))
FROM salespersons sp
LEFT JOIN sales s ON sp.id = s.spsn_id
GROUP BY sp.id, sp.name

LEFT JOIN 将返回销售人员,即使他们没有销售。

只要该用户没有销售,NVL 就会给你0

于 2013-11-12T19:26:58.480 回答
1

尝试以下

select sp.id, sp.name, sum(s.paid_amt)
  from salespersons sp
  left join sales s
    on sp.id = s.spsn_id
 group by sp.id, sp.name
于 2013-11-12T19:26:25.880 回答
0

Or try this:

with t as
(select spsn_id, sum(paid_amt) as totamt
  from Sales 
  group by spsn_id 
)
select sp.id, sp.name, coalesce( t.totamt, 0 )
  from salespersons sp
  left join t  ON sp.id = t.spsn_id

Which (theoretically) does the grouping before the join, thus saving time.

Coalesce does the same thing here as NVL, but is more portable.

于 2013-11-13T00:31:39.900 回答