Cómo seleccionar datos donde la suma es mayor que 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?

Hasta ahora lo he intentado:

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!

preguntado el 02 de febrero de 12 a las 10:02

Please post your table structure (.schema). -

2 Respuestas

Trata

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, en este caso.

Respondido 02 Feb 12, 14:02

on a similar note, if I wanted to count distinct uniqIDs where the quantity was more than 1, how would I do that? I have tried select count(distinct uniqID) from salesdata having sum(qty) >1, as well as select count(distinct uniqID) from salesdata group by uniqID having sum(qty) > 1 and neither of these have worked - EAndrews

The question you asking isn't quite valid. If you are asking for distinct uniqIDs, que qty do you use when there multiple rows with the same uniqID? - YXD

I'm guessing there should be a unique key on uniqID (not sure of the details in sqlite), so that you can't have any duplication. - YXD

if you want to put any condition on the result you get with group by you must use having.

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

you can put any of the condition with having normaly as in where.

having sumqty = 1 ,having sumqty < 1 ,having sumqty IN (1,2,3) etc..

Respondido 02 Feb 12, 15:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.