Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select multiple columns from a table, but group by one

Tags:

sql

group-by

The table name is "OrderDetails" and columns are given below:

OrderDetailID || ProductID || ProductName || OrderQuantity 

I'm trying to select multiple columns and Group By ProductID while having SUM of OrderQuantity.

 Select ProductID,ProductName,OrderQuantity Sum(OrderQuantity)  from OrderDetails Group By ProductID 

But of course this code gives an error. I have to add other column names to group by, but that's not what I want and since my data has many items so results are unexpected that way.

Sample Data Query:

ProductID,ProductName,OrderQuantity from OrderDetails

Results are below:

 ProductID     ProductName    OrderQuantity     1001          abc               5     1002          abc               23    (ProductNames can be same)     2002          xyz               8     3004          ytp               15     4001          aze               19     1001          abc               7     (2nd row of same ProductID) 

Expected result:

 ProductID     ProductName    OrderQuantity     1001          abc               12    (group by productID while summing)     1002          abc               23     2002          xyz               8     3004          ytp               15     4001          aze               19 

How do I select multiple columns and Group By ProductID column since ProductName is not unique?

While doing that, also get the sum of the OrderQuantity column.

like image 536
Ozan Ayten Avatar asked Jan 19 '14 14:01

Ozan Ayten


People also ask

Can we apply GROUP BY on multiple columns in SQL?

We can use the group by multiple column technique to group multiple records into a single record. All the records that have the same values for the respective columns mentioned in the grouping criteria can be grouped as a single column using the group by multiple column technique.

Do all columns in SELECT have to be in GROUP BY?

Answer. No, you can GROUP BY a column that was not included in the SELECT statement.


1 Answers

I use this trick to group by one column when I have a multiple columns selection:

SELECT MAX(id) AS id,     Nume,     MAX(intrare) AS intrare,     MAX(iesire) AS iesire,     MAX(intrare-iesire) AS stoc,     MAX(data) AS data FROM Produse GROUP BY Nume ORDER BY Nume 

This works.

like image 54
Urs Marian Avatar answered Sep 22 '22 08:09

Urs Marian