0

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

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

from

    consumes_t

group by
      consumes_t.item_id

我认为他们希望我们使用子查询,但我对此并不陌生,根本没有得到它。

4

3 回答 3

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
于 2013-10-22T23:59:06.330 回答
0

Try this:

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

from

    consumes_t
于 2013-10-23T00:00:40.717 回答
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
于 2013-10-23T00:37:59.897 回答