Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select data where sum is greater than x

I am very new to SQL and am using SQLite 3 to run basket analysis on sales data.

The relevant columns are the product ID, a unique transaction ID (which identifies the basket) and the product quantity. Where a customer has bought more than one product type, the unqiue transaction ID is repeated.

I am wanting to select only baskets where the customer has bought more than 1 item.

Is there any way on SQLite to select the unique transaction ID and the sum of the quantity, but only for unique transaction IDs where the quantity is more than one?

So far I have tried:

select uniqID, sum(qty) from salesdata where sum(qty) > 1 group by uniqID;

But SQLite gives me the error 'misuse of aggregate: sum()'

Sorry if this is a simple question but I am struggling to find any relevant information by googling!

like image 211
EAndrews Avatar asked Jan 17 '26 04:01

EAndrews


1 Answers

Try

select uniqID, sum(qty) from salesdata group by uniqID having sum(qty) > 1

"where" cannot be used on aggregate functions - you can only use where on uniqId, in this case.

like image 149
YXD Avatar answered Jan 19 '26 19:01

YXD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!