我有一个表 SAMPLE ,其中包含唯一列(sal_id,gal_id)和金额,税金,日期和更多列。
SAMPLE表
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。请帮帮我。
答案 0 :(得分: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';
Here是一个小提琴
更新:上一个答案假定max(日期)也有最大值(金额)。
一个更好的解决方案可以是:
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';
Here是小提琴