Skip to content
Advertisement

Is there a way to substitute GROUP BY

I have two tables i’m working with: comporder(quantity,cod(Fk on cod(product),cod_ship); product(cod(Pk),price); I need to produce a query that will give me the sum of the prices of the products that are in the comporder table for each cod_ship; I came up with this query:

However I am not allowed to use the GROUP BY function and I can’t seem to have the price where the quanity is above one. For exampe if in my comporder table I have:

And if in my product table I have:

If I apply my query the result will be:

When te actual result should be, based on the quantity of the products in the table comporder:

So I can’t seem to figure out how to get the sum also based on the quantity of the product and witouth the GROUP BY function, I should just show the sum as “output”, can somebody help me out understand how can I do it?

REPLYING TO COMMENTS: I cannot use group by due to an assignment. I am using PostgreSQL 12.1

Advertisement

Answer

As requested by the OP in the comments here is a solution using GROUP BY:

Edit:

Here is the solution without GROUP BY:

It works by first selecting a unique list of cod_ship ids (what we previously grouped the query by). Then we execute a subquery using the cod_ship id to calculate the sum for each column. We use the table alias results in order to reference the values in the parent query of the subquery.

SQL Fiddle Link

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement