Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to GROUP BY

I have the table with billID being the primary key:

Invoice (billID, item, value, quantity)

and the following query:

SELECT item, sum(quantity) AS TotalItems
FROM Invoice
WHERE value>1
GROUP BY item
HAVING sum(quantity)>10

I need to rewrite to optimize (or de-optimize?) using only SELECT, FROM and WHERE.

  1. What is the new query eliminating GROUP BY and HAVING?
  2. Is it always possible to eliminate GROUP BY & HAVING and use only SELECT, FROM and WHERE?

My approach:

[1] I am using UNION of different items to achieve this. But the major problem is that I need to know all the item before hand.

SELECT item, sum(quantity) FROM Invoice WHERE item='lumia'
UNION
SELECT item, sum(quantity) FROM Invoice WHERE item='iphone'
UNION
SELECT item, sum(quantity) FROM Invoice WHERE item='samsung'
UNION
SELECT item, sum(quantity) FROM Invoice WHERE item='moto'
.
.
.
and so on

Is there another way to get the result?

like image 279
sam Avatar asked Oct 21 '25 03:10

sam


1 Answers

we can use subquery and do summation of each item's quantity

SELECT A.item, A.Total
FROM
(  SELECT distinct item,
       (SELECT SUM(quantity)
        FROM Invoice I2 
        WHERE I2.item = I1.item) Total
FROM Invoice I1
) A
where Total >10
like image 156
radar Avatar answered Oct 22 '25 19:10

radar