Oracle SQL using group by: Can you group by a field used to join two tables? -


select b.first_name, b.last_name, sum(t.price_total) brokers b left outer join trades t on b.broker_id=t.broker_id group b.broker_id 

my problem question asks 'display total value of each broker's trades'. answer groups b.first_name||' '||b.last_name, think group should done via broker's id (i.e. 2 people same name grouped together, wouldn't happen via broker id).

yet when running code, error

ora-00979: not group expression 00979. 00000 -  "not group expression" *cause:     *action: error @ line: 1 column: 8 

my question is, why can't use b.broker_id column group by?

try this:

select b.broker_id, b.first_name, b.last_name, sum(t.price_total) brokers b left outer join trades t on b.broker_id=t.broker_id group b.broker_id, b.first_name, b.last_name 

when use group by, select clause can have columns specified in group , aggregated/calculated fields group sum, average, min, max etc.

you can use analytic functions overcome it, used avoid self joins , fields require while doing aggregations:

select distinct * (select b.first_name, b.last_name,  sum(t.price_total) on (partition b.broker_id) price_total brokers b left outer join trades t on b.broker_id=t.broker_id); 

Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

css - Can I use the :after pseudo-element on an input field? -