试图用总和找到最大值

时间:2013-10-22 23:53:36

标签: sql sum max

我只想显示最大数量的总数量。这给了我整个清单。

select 
      sum (consumes_t.quantity) as totalquantity
        , consumes_t.item_id

from

    consumes_t

group by
      consumes_t.item_id

我认为他们希望我们使用子查询,但我是新手,根本就没有得到它。

3 个答案:

答案 0 :(得分:1)

我还没有完成理解你想要的东西,但如果你想要最大数量在同一个查询上做:

SELECT SUM(consumes_t.quantity) as totalquantity, 
       MAX(consumes_t.quantity),
       consumes_t.item_id
FROM consumes_t 
GROUP BY consumes_t.item_id

答案 1 :(得分:0)

试试这个:

select MAX(sum (consumes_t.quantity))) as totalquantity
        , consumes_t.item_id

from

    consumes_t

答案 2 :(得分:0)

对于sqlserver,我认为你会使用TOP 1而不是下面发布的限制:

SELECT TOP 1 SUM(quantity) AS totalquantity
      ,item_id
  FROM consumes_t
  GROUP BY item_id
  ORDER BY SUM(quantity) DESC LIMIT 1;

但是如果有几个具有相同MAX的项目,您想要什么行为?然后使用子查询方法而不是限制或顶部。

postgres=# CREATE TABLE consumes_t(quantity int, item_id int);
CREATE TABLE
postgres=#
postgres=# INSERT INTO consumes_t VALUES(2, 1);
INSERT 0 1
postgres=# INSERT INTO consumes_t VALUES(3, 1);
INSERT 0 1
postgres=# INSERT INTO consumes_t VALUES(1, 2);
INSERT 0 1
postgres=# INSERT INTO consumes_t VALUES(1, 3);
INSERT 0 1
postgres=# INSERT INTO consumes_t VALUES(1, 3);
INSERT 0 1
postgres=# INSERT INTO consumes_t VALUES(10,4);
INSERT 0 1
postgres=# INSERT INTO consumes_t VALUES(7, 5);
INSERT 0 1
postgres=#
postgres=#
postgres=# SELECT SUM(quantity) AS totalquantity
postgres-#       ,item_id
postgres-#   FROM consumes_t
postgres-#   GROUP BY item_id;
 totalquantity | item_id
---------------+---------
            10 |       4
             5 |       1
             7 |       5
             2 |       3
             1 |       2
(5 rows)


postgres=#
postgres=# SELECT SUM(quantity) AS totalquantity
postgres-#       ,item_id
postgres-#   FROM consumes_t
postgres-#   GROUP BY item_id
postgres-#   ORDER BY SUM(quantity) DESC LIMIT 1;
 totalquantity | item_id
---------------+---------
            10 |       4
(1 row)

这是一个子查询方法,返回两个项目共10个的记录:

INSERT INTO consumes_t VALUES(3, 5);

WITH totals AS (
    SELECT SUM(quantity) AS totalquantity
           ,item_id
       FROM consumes_t
       GROUP BY item_id
)
SELECT t.item_id, t.totalquantity
  FROM totals t
  WHERE t.totalquantity = ( SELECT MAX(totalquantity)
                              FROM totals )
  ORDER BY item_id
相关问题