I have a table which I need to make a calculated field with the total compensation for employees who have count(distinct(pay_type)) > 1.
When count(distinct(pay_type)) > 1 is true I want the total amount in a column next to the amount column.
My approach was to use a window function along with some kind of CASE statement, but can't figure it out.
My current query is:
Select check_num, emp_id, name, pay_type, sum(amount) as amt
from employee_paystubs
group by check_num, emp_id, name, pay_type
order by check_num desc;
This is the resulting data:
| CHECK_NUM | EMP_ID | NAME | PAY_TYPE | AMT |
|---|---|---|---|---|
| 01 | 1 | JEFF | SALARY | 1500 |
| 02 | 2 | BOB | SALARY | 2000 |
| 03 | 2 | BOB | SALARY | 2000 |
| 04 | 2 | BOB | BONUS | 1000 |
| 05 | 5 | JAKE | SALARY | 1800 |
| 06 | 6 | MEGAN | SALARY | 1900 |
This is my desired output:
| CHECK_NUM | EMP_ID | NAME | PAY_TYPE | AMT | NEW_COL |
|---|---|---|---|---|---|
| 01 | 1 | JEFF | SALARY | 1500 | |
| 02 | 2 | BOB | SALARY | 2000 | |
| 03 | 2 | BOB | SALARY | 2000 | |
| 04 | 2 | BOB | BONUS | 1000 | 5000 |
| 05 | 5 | JAKE | SALARY | 1800 | |
| 06 | 6 | MEGAN | SALARY | 1900 |
Thank you.
PS I am using Oracle.
One option is to use Case expression that checks for number of distinct PAY_TYPES (per EMP_ID) - and if it is > 1 (haave both: SALARY and BONUS) - fetches the Sum(AMT) in BONUS row....