tags:

views:

88

answers:

5
+5  Q: 

SQL most popular

I have a mysql table with items in relation to their order.


CREATE DATABASE IF NOT EXISTS `sqltest`;
USE `sqltest`;

DROP TABLE IF EXISTS `testdata`;
CREATE TABLE `testdata` (
  `orderID` varchar(10) DEFAULT NULL,
  `itemID` varchar(10) DEFAULT NULL,
  `qtyOrdered` int(10) DEFAULT NULL,
  `sellingPrice` decimal(10,2) DEFAULT NULL
)

INSERT INTO `testdata`(`orderID`,`itemID`,`qtyOrdered`,`sellingPrice`) 
values ('1','a',1,'7.00'),('1','b',2,'8.00'),('1','c',3,'3.00'),('2','a',1,'7.00'),('2','c',4,'3.00');

Intended Result:

A = (1+1)2

B = 2

C = (2+4)6 <- most popular


How do I add up all the qty's for each item and result the highest one?

It should be fairly strait forward but I'm new to SQL and I can't work this one out :S

Solution needs to be mysql and or php.

I guess there needs to be some sort of temporary tally variable for each item ID, but that seems like it could get messy with too many items.


ANSWER:

(thanks nuqqsa)

SELECT itemID, SUM(qtyOrdered) AS total FROM testdata GROUP BY itemID ORDER BY total DESC LIMIT 1;
A: 
select count(qtyOrdered), qtyOrdered from testdata group by qtyOrdered
Grumpy
this won't give the expected result, because it isn't ordered by the total amount - it will give the item with the bigest single amount at first and so on...
oezi
+6  A: 

How about this:

SELECT itemID, SUM(qtyOrdered) AS total FROM testdata GROUP BY itemID ORDER BY total DESC;
nuqqsa
I f***ing lover stacked. A+
Brae
A: 

SELECT itemID, SUM(qtyOrdered) as blah FROM sqltest GROUP BY itemID ORDER BY blah DESC should do it

oezi
gives me an error: "You have an error in your SQL syntax"probly cuz count() is empty
Brae
A: 
SELECT      *
FROM        testdata
ORDER BY    SUM(gtyOrdered) DESC
GROUP BY    itemID
Coronatus
A: 
SELECT SUM( qtyOrdered ) AS sum_ordered, itemID
FROM testdata
GROUP BY itemID
ORDER BY sum_ordered
powtac