试图获取从不同行收集的总和的最大值

时间:2013-10-25 01:21:49

标签: sql sql-server sum max

我知道这个问题一直被问到,但我是sql的新手,似乎无法从其他问题中得到答案。我有一张表consumes_t),其中包含date_recieveditem_idpatient_idquantitytime_recieved。我需要找出最消耗的项目。

我写过这个剧本:

select sum (quantity) as sumquantity, item_id
from consumes_t as highquantity_t

where quantity > all

(select quantity
from consumes_t as allotherquantity_t
where highquantity_t.quantity > allotherquantity_t.quantity)

group by item_id

它为我提供了所有项目及其总数的列表,但我只希望显示最高总数。我不能使用top1和order by。

我也试过了:

select max (totalquantity) as consumed, item_id
from consumes_t
join (select 
    sum (consumes_t.quantity) as totalquantity 
    from consumes_t
    group by consumes_t.item_id) as t1
 on t1.totalquantity > consumes_t.quantity
 group by item_id

这给了我所有item_ids总计'9'。

任何想法都会非常感激。感谢。

1 个答案:

答案 0 :(得分:1)

我使用CTE来获得所需的结果

WITH A AS
(
SELECT item_id, SUM(quantity) AS TotalQuantity
FROM consumes_t
GROUP BY item_id
)

SELECT item_id, TotalQuantity
FROM A
WHERE TotalQuantity = (SELECT MAX(TotalQuantity) FROM A)