Два метода - один с использованием MIN
и CASE
, а другой с использованием MIN
и PIVOT
SQL Fiddle
Oracle11g Настройка схемы R2 :
CREATE TABLE table_name ( PersonId, BankAcc, TransactionNo, TransYear, method) as
select 1, 10, 1, 2011, 'check' from dual union
select 1, 10, 5, 2012, 'card' from dual union
select 2, 11, 7, 2012, 'check' from dual union
select 2, 15, 10, 2012, 'check' from dual union
select 2, 15, 11, 2014, 'card' from dual union
select 2, 15, 14, 2016, 'card' from dual union
select 2, 19, 15, 2009, 'check' from dual union
select 2, 19, 16, 2015, 'card' from dual union
select 3, 20, 25, 2017, 'check' from dual union
select 3, 21, 34, 2015, 'check' from dual union
select 3, 21, 51, 2017, 'card' from dual;
Запрос 1 :
SELECT PersonID,
BankAcc,
MIN( CASE method WHEN 'card' THEN TransYear END )
- MIN( CASE method WHEN 'check' THEN TransYear END ) AS diff
FROM table_name
GROUP BY PersonID,
BankAcc
ORDER BY PersonID,
BankAcc
Результаты :
| PERSONID | BANKACC | DIFF |
|----------|---------|--------|
| 1 | 10 | 1 |
| 2 | 11 | (null) |
| 2 | 15 | 2 |
| 2 | 19 | 6 |
| 3 | 20 | (null) |
| 3 | 21 | 2 |
Запрос 2 :
SELECT PersonId,
BankAcc,
crd - chk AS diff
FROM ( SELECT PersonId, BankAcc, TransYear, method FROM table_name )
PIVOT( MIN( transyear ) FOR method IN ( 'check' AS chk, 'card' AS crd ) )
ORDER BY PersonID, BankAcc
Результаты :
| PERSONID | BANKACC | DIFF |
|----------|---------|--------|
| 1 | 10 | 1 |
| 2 | 11 | (null) |
| 2 | 15 | 2 |
| 2 | 19 | 6 |
| 3 | 20 | (null) |
| 3 | 21 | 2 |