ORACLE SQL按编号仅选择每组的MAX

时间:2016-07-08 21:53:36

标签: sql oracle

我在为特定时期选择特定Acc,Nam的余额总和时遇到问题。

SELECT Acc, Nam, SUM(Bal) FROM table WHERE
MAX(Par) = (SELECT Par WHERE Acc IN (101,102) AND Dat >1105 AND Dat <1405)
AND Acc IN (101,102) AND Dat >1105 AND Dat <1405
GROUP BY Acc, Nam


Acc --- Nam --- Bal --- Par --- Dat
101 --- One --- 150 --- 131 --- 1205
101 --- One --- 120 --- 132 --- 1205
101 --- One --- 160 --- 133 --- 1305
102 --- Two --- 190 --- 121 --- 1205
102 --- Two --- 110 --- 122 --- 1305
102 --- Two --- 150 --- 123 --- 1305

最终输出应为:

Acc --- Nam --- Bal
101 --- One --- 280
102 --- Two --- 340

因此,它将按帐户和帐户名称分隔的期间内的所有余额的总和。只有每天最高Par数的余额应总计合计。请指教。

更新

我用下面的row_number方法做了,但我收到的只是所有行的总数(没有一些)。以下是显示的代码:两个帐户,两个帐户说明,参数,日期和余额。我希望看到两行,它们是给定帐户范围内所有日期的总和,并且在一天内具有最高参数编号。最终输出应该只有三列:帐户,名称和余额。此查询应该能够选择每天的最大参数,并将所有这些最大值汇总到一个帐户。

 SELECT h.account, h.name, h.paramet, h.date, h.balance 
    FROM h
    WHERE TRUNC(h.date) > '01-Jun-16' AND TRUNC(h.date) < '10-Jun-16' 
    AND h.account IN ('410212','410213') 
    AND h.fund LIKE 'SSPSP

2 个答案:

答案 0 :(得分:3)

您可以使用row_number()

SELECT Acc, Nam, SUM(Bal)
FROM (SELECT t.*,
             ROW_NUMBER() OVER (PARTITION BY Acc, Nam, Dat ORDER BY Par DESC) as seqnum
      FROM table t
      WHERE Acc IN (101,102) AND Dat > 1105 AND Dat < 1405
     ) t
WHERE seqnum = 1
GROUP BY Acc, Nam;

答案 1 :(得分:0)

我有下一个与上述查询相关的问题。如何创建一个表,其中两个SUM(Bal)列彼此具有不同的Date:

Acc --- Nam --- Bal(Dat1) - Bal(Dat2)
101 ---一个------- 280 ---------- 300
102 ---两个------- 340 ---------- 180

SELECT Acc, Nam, SUM(Bal)
FROM (SELECT t.*,
             ROW_NUMBER() OVER (PARTITION BY Acc, Nam, TRUNC(Dat) ORDER BY Par DESC) as seqnum
      FROM table t
      WHERE Acc IN (101,102) AND Dat = 1105 
     ) t
WHERE seqnum = 1
GROUP BY Acc, Nam;

SELECT Acc, Nam, SUM(Bal)
FROM (SELECT t.*,
             ROW_NUMBER() OVER (PARTITION BY Acc, Nam, TRUNC(Dat) ORDER BY Par DESC) as seqnum
      FROM table t
      WHERE Acc IN (101,102) AND Dat = 1405
     ) t
WHERE seqnum = 1
GROUP BY Acc, Nam;