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.
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.
Answer. No, you can GROUP BY a column that was not included in the SELECT statement.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With