select tt.threshold_id
from (select sum(amount) over (partition by tt.threshold_type
order by tt.threshold_type ) amt
from cash_transactions) cash,
thresholds tt
where tt.threshold_amount < cash.amt
the rdms involved is oracle the error is
" ORA-00904: "TT"."THRESHOLD_TYPE": invalid identifier"
what i want to do with this query is :
- threshold table contains a column threshold type which contain column name of the cash transactions table
- And for each record from the threshold table we need to compare the sum(amount) group by the threshold type from cash transactions table .
- and the amount fetched is compared with the threshold_amount of the the threshold table
- and i need to select the threshold_id
Thresholds Table:
Threshold_id Threshold_type Threshold_amount
============================================================
threshold_1 p_id 450
threshold_2 p_id,to_acc_main_num 100
Cash Transactions Table:
Tran_inst_id p_id amount to_acc_main_num
=================================================
1 E1 100 123
2 E2 200 5765
3 E1 200 687
4 E2 300 890
5 E1 100 462
DESIRED OUTPUT :
Lets take the first fetch :the first record from the threshold table
Threshold_id Threshold_type Threshold_amount
============================================================
threshold_1 p_id 100000
1.now the threshold_type is p_id ok
2.So i need to group by pid from cash_transactions table.
3.so the desired result from this is (but i have to take sum on basis of p_id only)
not tran_inst_id in this case
Tran_inst_id p_id sum(amount)
======================================
1 E1 400
2 E2 500
3 E1 400
4 E2 500
5 E1 400
1.now each records amount above is compared with the amount of threshold_1 record.
2.so 450 threshold_amount for threshold_1 is compared with all the above record
3.so the required output will be
theshold_id Tran_inst_id
==================================
thresold_1 2
threshold_1 4
- the above result is for first record of threshold table ,now the same continues for the second record.
EDIT:Suppose if the threshold_type is null ,then we not need to include partition by part in the query ,then how it can be obtain?
It is only possible with dynamic sql, since the number of columns in the group by clause is variable.
For example with a function:
and then
EDIT due to new requirements: