数据集和总和的最小值

时间:2019-01-16 06:28:50

标签: sql oracle

我有数据:

ID  DUE         AMT
4   2018-03-10  335.75
3   2018-04-10  334.75
1   2018-05-10  333.75
2   2018-06-10  332.75

我需要提取:

  1. 最少到期(03-10)
  2. 最低应付款额(335.75)
  3. amt列的总和。

可以在单个查询中完成吗?

2 个答案:

答案 0 :(得分:5)

尝试保持密集排名:

with tt as (
  select 4 id, date '2018-03-10' due, 335.75 amt from dual union all
  select 3 id, date '2018-04-10' due, 334.75 amt from dual union all
  select 1 id, date '2018-05-10' due, 333.75 amt from dual union all
  select 2 id, date '2018-06-10' due, 332.75 amt from dual
)
select min(due) least_due,
       min(amt) keep (dense_rank first order by due) amt_for_least_due,
       sum(amt) sum_amt
from   tt

答案 1 :(得分:4)

我们可以在这里尝试使用解析函数:

WITH cte AS (
    SELECT ID, DUE, AMOUNT,
        SUM(AMOUNT) OVER () AS TOTALAMOUNT,
        ROW_NUMBER() OVER (ORDER BY DUE) rn
    FROM yourTable
)

SELECT ID, DUE, AMOUNT, TOTALAMOUNT
FROM cte
WHERE rn = 1;