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
.
GROUP BY
and HAVING
?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?
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
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