我有一个简单的任务,但我被困住了,我有一张桌子,需要打印出最大销售总额的ID。我已设法根据每个销售额的总和打印一份已排序的ID列表:
SELECT "COMPANY"."ID", SUM("COMPANY"."PRICE") As PriceSum
FROM "COMPANY"
WHERE "COMPANY"."DATEOFSALE" >= DATE '2016-01-01'
GROUP BY "COMPANY"."ID"
ORDER BY PriceSum DESC;
我只想显示最畅销公司的ID和总销售额。 TIA
这是在Oracle中,所以我不能便宜并且使用LIMIT 1。
答案 0 :(得分:2)
您可以改为使用子查询:
SELECT c.*
FROM (SELECT "COMPANY"."ID", SUM("COMPANY"."PRICE") As PriceSum
FROM "COMPANY"
WHERE "COMPANY"."DATEOFSALE" >= DATE '2016-01-01'
GROUP BY "COMPANY"."ID"
ORDER BY PriceSum DESC
) c
WHERE rownum = 1;
在Oracle 12c +中,您可以在没有子查询的情况下使用FETCH FIRST 1 ROW ONLY
。这是ANSI标准等效于LIMIT
。
编辑:
如果您想要所有公司,请使用rank()
或dense_rank()
:
SELECT c.*
FROM (SELECT "COMPANY"."ID", SUM("COMPANY"."PRICE") As PriceSum,
RANK() OVER (ORDER BY SUM("COMPANY"."PRICE") DESC) as seqnum
FROM "COMPANY"
WHERE "COMPANY"."DATEOFSALE" >= DATE '2016-01-01'
GROUP BY "COMPANY"."ID"
ORDER BY PriceSum DESC
) c
WHERE seqnum = 1;
您可以将RANK()
替换为ROW_NUMBER()
并获取之前的结果。