0

我有一个表SAMPLE具有唯一列(sal_id、gal_id)和金额、税款、日期和更多列。

样品表

 actual_id, sal_id, gal_id, processed_flag, amount, tax     date    
   1          101     201     Y             10       1     25-Aug-12  
   2          101     201     Y             20       3     27-Aug-12  
   3          101     201     N             15       2     29-Aug-12  

现在我需要找出最大日期的未处理数据(process_flag='N')和继续数据(process_flag='Y')之间的区别。我需要计算 (sal_id + gal_id) 组合的金额和税金之间的差异。

所以查询返回应该是这样的:

在此示例中,由于对于 (101, 201),我们有 2 个已处理的行,并且 (actual_id 2 具有最大日期。因此需要找到 actual_id 3 和 actual_id 2 行之间的差异。

actual_id,  sal_id,  gal_id, total_amount, total_tax  date    
    3          101     201    -5 (15-20)    -1 (2-3)   29-Aug-12   

我正在使用 Oracle 11g。请帮我。

4

1 回答 1

1

试试这个:

WITH t AS (SELECT DISTINCT "sal_id" sid,"gal_id" gid,"processed_flag" pf, max("amount") over
(partition BY "sal_id","gal_id","processed_flag") am,
max("tax") over
(partition BY "sal_id","gal_id","processed_flag") tx,
           max("actual_id") over
(partition BY "sal_id","gal_id","processed_flag") aid,
           max("date") over
(partition BY "sal_id","gal_id","processed_flag") dt
FROM sample)
SELECT t1.aid, t1.sid, t1.gid, t1.am-t2.am, t1.tx-t2.tx, t1.dt FROM t t1 JOIN t t2 ON t1.sid=t2.sid AND t1.gid=t2.gid
WHERE t1.pf='N' AND t2.pf='Y';

是一个小提琴


更新:前面的答案假设 max(date) 也有 max(amount)。
一个更好的解决方案可以是:

WITH t AS (SELECT *
FROM sample s
WHERE s."date" = (SELECT max("date") FROM sample s_in
                WHERE s_in."sal_id" = s."sal_id"
                AND s_in."gal_id" = s."gal_id"
                AND s_in."processed_flag" = s."processed_flag"))
SELECT t1."actual_id", t1."sal_id", t1."gal_id", t1."amount"-t2."amount" total_amount, t1."tax"-t2."tax" total_tax, t1."date"
FROM t t1 JOIN t t2 ON t1."sal_id"=t2."sal_id" AND t1."gal_id"=t2."gal_id"
WHERE t1."processed_flag"='N' AND t2."processed_flag"='Y';

是小提琴

于 2012-09-03T08:55:46.643 回答