SQL最受欢迎

时间:2010-05-17 09:40:09

标签: php mysql

我有一个mysql表,其中包含与其订单相关的项目。


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');

预期结果:

A =(1 + 1)2

B = 2

C =(2 + 4)6< - 最受欢迎


如何为每个项目添加所有数量并得出最高的数量?

它应该是相当紧张的前进,但我是SQL的新手,我无法解决这个问题:S

解决方案需要是mysql和/或php。

我想每个商品ID都需要某种临时的tally变量, 但是看起来它可能会因太多物品而变得混乱。


解答:

(感谢nuqqsa)

SELECT itemID, SUM(qtyOrdered) AS total FROM testdata GROUP BY itemID ORDER BY total DESC LIMIT 1;

5 个答案:

答案 0 :(得分:6)

这个怎么样:

SELECT itemID, SUM(qtyOrdered) AS total FROM testdata GROUP BY itemID ORDER BY total DESC;

答案 1 :(得分:0)

SELECT itemID, SUM(qtyOrdered) as blah FROM sqltest GROUP BY itemID ORDER BY blah DESC应该这样做

答案 2 :(得分:0)

SELECT      *
FROM        testdata
ORDER BY    SUM(gtyOrdered) DESC
GROUP BY    itemID

答案 3 :(得分:0)

SELECT SUM( qtyOrdered ) AS sum_ordered, itemID
FROM testdata
GROUP BY itemID
ORDER BY sum_ordered

答案 4 :(得分:-4)

select count(qtyOrdered), qtyOrdered from testdata group by qtyOrdered