dynamic pivoting - oracle11g

I am hoping to get some help on a view which needs to be pivoted, I am not sure though.
View is in following format:
CASE CASE_ORDER MANAGER MONTHLY_CASES FISCAL_CASES
case_1 1 John 15 84
case_1 1 Jeff 10 80
case_2 2 John 20 90
case_2 2 Jeff 13 65
case_3 3 John 7 72
case_3 3 Jeff 17 70
My final chart should look like the following:
CASE CASE_ORDER JOHN_CURR_MONTH JOHN_FY JOHN_CURR_MONTH JOHN_FY
case_1 1 15 84 10 80
case_2 2 20 90 13 65
case_3 3 7 72 17 70
My problem is that managers can change and so does the number of managers from month to month,
so I can't hard code their names (ie. 'mgr1' and 'mgr2') and use DECODE. It has to be dynamic...

Thanks for your suggestion, I figured it out. In fact there is a similar answer in tom kyte's blog (http://www.oracle.com/technetwork/issue-archive/2012/12-jul/o42asktom-1653097.html) which I modified for my purpose. Here it is:
CREATE OR REPLACE PROCEDURE dynamic_pivot_proc ( p_cursor IN OUT SYS_REFCURSOR )
AS
l_query LONG := 'SELECT case_order, case';
BEGIN
FOR x IN (SELECT DISTINCT manager FROM test_table ORDER BY 1 )
LOOP
l_query := l_query ||
REPLACE( q'|, MAX(DECODE(manager,'$X$',monthly_total)) $X$_current_month|',
'$X$', dbms_assert.simple_sql_name(x.manager) ) ||
REPLACE( q'|, MAX(DECODE(manager,'$X$',fiscal_total)) $X$_fy|',
'$X$', dbms_assert.simple_sql_name(x.manager) );
END LOOP;
l_query := l_query || ' FROM test_table
GROUP BY case_order, case
ORDER BY case_order ';
OPEN p_cursor FOR l_query;
END;
SQL> variable x refcursor;
SQL> exec dynamic_pivot_proc( :x );
SQL> print x
CASE CASE_ORDER JEFF_CURRENT_MONTH JEFF_FY JOHN_CURRENT_MONTH JOHN_FY
1 case_1 10 80 15 84
2 case_2 13 65 20 90
3 case_3 17 70 7 72
Now the thing is instead of printing the result I want to store it in a view. How do I achieve that? I tried to modify the line
l_query LONG := 'SELECT case_order, case';
with
l_query LONG := 'CREATE OR REPLACE VIEW SELECT case_order, case';
Needless to say that it did not work because CREATE OR REPLACE is a DDL statement, so some how I have to use EXECUTE IMMEDIATE.
Any suggestion? Thanks in advance.

Related

Oracle 'MEMBER OF' function

I was trying to use MEMBER OF function but receiving error "PLS-00306: wrong number or types
of arguments in call to 'MEMBER OF'.". Please let me know, how i can use 'MEMBER OF' function
correctly, i want to avoid iteration.
Table: Employee
EMP_ID EMP_NAME EMP_BRANCH
1 Oliver 104
2 Harry 105
3 Jack 105
4 Jacob 103
DECLARE
TYPE emp_name_type IS RECORD(emp_name employee.emp_name%type);
TYPE emp_name_table_type IS TABLE OF emp_name_type;
emp_name_table_type_array emp_name_table_type;
BEGIN
select x.emp_name BULK COLLECT
into emp_name_table_type_array
from (
select e.emp_name, min(e.emp_id) as emp_id
from employee e
where e.emp_branch = 105
group by e.emp_name
) x
order by x.emp_id;
-- receiving output Harry + Jack
FOR i IN emp_name_table_type_array.FIRST .. emp_name_table_type_array.LAST LOOP
dbms_output.put_line(emp_name_table_type_array(i).emp_name);
END LOOP;
-- here i want to implement something like bellow using 'Member OF' function
IF 'Harry' MEMBER OF emp_name_table_type_array THEN
dbms_output.put_line('yes');
ELSE
dbms_output.put_line('no');
END IF;
END;
/
Thank you
You have one type declaration too many (and have to fix the first dbms_output.put_line call because of that).
SQL> DECLARE
2 TYPE emp_name_table_type IS TABLE OF employee.emp_name%type;
3 emp_name_table_type_array emp_name_table_type;
4 BEGIN
5 select x.emp_name BULK COLLECT
6 into emp_name_table_type_array
7 from (
8 select e.emp_name, min(e.emp_id) as emp_id
9 from employee e
10 where e.emp_branch = 105
11 group by e.emp_name
12 ) x
13 order by x.emp_id;
14
15 -- receiving output Harry + Jack
16 FOR i IN emp_name_table_type_array.FIRST .. emp_name_table_type_array.LAST LOOP
17 dbms_output.put_line(emp_name_table_type_array(i));
18 END LOOP;
19
20 -- here i want to implement something like bellow using 'Member OF' function
21 IF 'Harry' MEMBER OF emp_name_table_type_array THEN
22 dbms_output.put_line('yes');
23 ELSE
24 dbms_output.put_line('no');
25 END IF;
26 END;
27 /
Harry
Jack
yes
PL/SQL procedure successfully completed.
SQL>

Update Column using Rownum

I am trying to update a column based on the rownumber. Table Unpaid1 contain multiple transactions for alot of accounts. When i execute the following script, I often end up transactions With incorrect sequential number (Cycleage) like shown below. The cycleage should be in the order 1 to 4 from oldest to newest. What might be the cause of this issue? Is there another way to assign the cycleage?
Begin
For X in (Select * From temp_Unpaid1 order by trxnserno asc)
loop
Update temp_Unpaid1 t set t.cycleage = rownum where t.custid=x.custid;
end loop;
End;
+-----------+-----------+--------+--------+----------+
| TRXNSERNO | CUSTID | AMOUNT | DATE | CYCLEAGE |
+-----------+-----------+--------+--------+----------+
| 66 | 45 | -10 | 08.jan | 2 |
| 67 | 45 | -20 | 10.jan | 1 |
| 90 | 45 | -30 | 15.jan | 3 |
| 155 | 45 | -15 | 20.jan | 4 |
+-----------+-----------+--------+--------+----------+
The catch is that the ROWNUM in the update is independent of the SELECT statement and, in fact, it looks like you are doing unnecessary updates. Here's why:
The SELECT will return all rows in the order of TRXNSERNO and even if you have only the one custid, you'll get 4 rows with the same custid:
CUSTID TRXNSERNO ...(other columns)
45 66
45 67
45 90
45 155
Then for each of these rows, the update statement will run (so you'll be updating the same 4 rows 4 times.)
When the UPDATE runs, it finds the 4 rows for custid 45 (it doesn't know/care what the TRXNSERNO was in the SELECT) and updates them in whatever order it finds them. (There's nothing in the UPDATE statement that forces the order of the rows as they are updated.)
So, whatever order the (4th and last) update found them in is how the ROWNUM values will be assigned so if Oracle found them in the order of
CUSTID TRXNSERNO
45 67
45 66
45 90
45 155
Then the ROWNUM value will be in that order:
CUSTID TRXNSERNO ROWNUM
45 67 1
45 66 2
45 90 3
45 155 4
In another run (depending on circumstances) Oracle might execute the update and find the custid 45 rows in a completely different order like the following and assign them rownums accordingly:
CUSTID TRXNSERNO ROWNUM
45 155 1
45 66 2
45 90 3
45 67 4
You could keep your current code but just generate the ROWNUMs in the SELECT list and apply the value in the update to the custid/trxnserno pairs:
Begin
For X in
(Select tmp.*
, row_number() over (partition by tmp.custid order by tmp.trxnserno) as rn
From temp_Unpaid1 tmp)
loop
Update temp_Unpaid1 t
set t.cycleage = rn
where t.custid=x.custid
and t.trxnserno = x.trxnserno;
end loop;
End;
Alternatively, you could try this in a single SQL statement using something like MERGE and using only the WHEN MATCHED portion of it:
MERGE INTO temp_unpaid1 temp
USING
(Select t.*
, row_number() over (partition by custid order by trxnserno) as rn
From temp_Unpaid1
) rn_qry
ON (temp.custid = rn_qry.custid
AND temp.trxnserno = rn_qry.trxnserno
)
WHEN MATCHED THEN
UPDATE SET
temp.cyclage = rn_qry.rn
;
Note: unfortunately I can't test the accuracy of the syntax right now, but hopefully this is of some value. :)

PL/SQL Return Only 1 Row for Each Grouping

I have table that lists items like below. It basically has Operation Numbers (OP_NO) that tell where a product is at in the process. These OP Numbers can be either Released or Completed. They follow a process as in 10 must happen before 20, 20 must happen before 30 etc. However users do not update all steps in reality so we end up with some items out of order complete while the earlier steps are not as show below (OP30 is completed but OP 10 and 20 are not).
I basically want to produce a listing of each ORDER_ID showing the furthest point of completion for each ORDER_ID. I figured I could do this by querying for STATUS = 'Completed' and Sorting by OP_NO Desc. However I can't figure out how to produce only 1 result for each ORDER_ID. For example in ORDER_ID 345 Steps 10 and 20 are completed. I would only want to return that STEP 20 is where it is currently at. I was figuring I could do this with 'WHERE ROWNUM <= 1' but haven't had much luck. Could any experts weigh in?
Thanks!
ORDER_ID | ORDER_SEC | ORDER_RELEASE | OP_NO | STATUS | Description
123 2 3 10 Released Op10
123 2 3 20 Released Op20
123 2 3 30 Completed Op30
123 2 3 40 Released Op40
345 1 8 10 Completed Op10
345 1 8 20 Completed Op20
345 1 8 30 Released Op30
345 1 8 40 Released Op40
If I understand correctly what you want the below should do what you need. Just replace test table with your table name.
select *
from test_table tst
where status = 'Completed'
and op_no = (select max(op_no)
from test_table tst1
where tst.order_id = tst1.order_id
and status = 'Completed');
Given your sample data this produced the below results.
Order_Id Order_Sec Order_Release op_no Status Description
123 2 3 30 Completed Op30
345 1 8 20 Completed Op20
Cheers
Shaun Peterson

Union and Count Collections in Neo4j

My simple database contains nodes of 'terms' and 'codes' linked to each other.
There are two types of relationships.
Relationships between 'terms' and 'codes' called :CODE and are undirected (or read in both directions equally).
Relationships between 'terms' called :NT (which means narrow term) and are directed.
I want to walk thru all the 'terms' from top to bottom and collect all the unique codes and count them.
This is my query:
MATCH (a)-[:NT*]->(b), (a)-[:CODE]-(c), (b)-[:CODE]-(d)
WHERE a.btqty = 0
RETURN a.termid AS termid, a.maxlen AS maxlen, COUNT(DISTINCT c.code) + COUNT(DISTINCT d.code) AS total, COLLECT(DISTINCT c.code) + COLLECT(DISTINCT d.code) AS codes
ORDER BY termid;
This is what I get:
termid maxlen total codes
22 2 3 ["S70","S43","S70"]
25 4 9 ["S20","S21","S54","S61","S63","S63","S21","S61","S54"]
26 2 9 ["S99","S98","S29","S13","S13","S20","S29","S14","S15"]
68 5 13 ["S38","S11","S12","S11","S12","S38","S37","S21","S36","S22","S98","S63","S58"]
123 2 3 ["S38","S12","S12"]
154 2 2 ["S58","S58"]
155 4 3 ["S63","S62","S63"]
159 2 2 ["S36","S36"]
...
I need to get rid of duplicates in collection and count them properly like this:
termid maxlen total codes
22 2 2 ["S43","S70"]
25 4 5 ["S20","S21","S54","S61","S63"]
26 2 7 ["S99","S98","S29","S13","S20","S14","S15"]
68 5 10 ["S38","S11","S12","S37","S21","S36","S22","S98","S63","S58"]
123 2 2 ["S38","S12"]
154 2 1 ["S58"]
155 4 2 ["S63","S62"]
159 2 1 ["S36"]
...
I think this is something about REDUCE function to apply but I do not know how to use it.
Thank you for your help!
You're right, this can be solved using REDUCE. Inside the reduce you need to check if the current element already exists in the accumulator and conditionally amend it:
MATCH (a)-[:NT*]->(b), (a)-[:CODE]-(c), (b)-[:CODE]-(d)
WHERE a.btqty = 0
WITH a.termid AS termid, a.maxlen AS maxlen,
REDUCE(uniqueCodes=[],
x in COLLECT(DISTINCT c.code) + COLLECT(DISTINCT d.code) |
CASE WHEN x IN uniqueCodes THEN uniqueCodes ELSE uniqueCodes+x END
) AS codes
ORDER BY termid
RETURN termid, maxlen, count(codes) as total, codes

Ref cursor with dynamic columns

I am using oracle 11g and have written a stored procedure which stores values in temporary table as follows:
id count hour age range
-------------------------------------
0 5 10 61 10-200
1 6 20 61 10-200
2 7 15 61 10-200
5 9 5 61 201-300
7 10 25 61 201-300
0 5 10 62 10-20
1 6 20 62 10-20
2 7 15 62 10-20
5 9 5 62 21-30
1 8 6 62 21-30
7 10 25 62 21-30
10 15 30 62 31-40
now using this temp table i want to return two cursors. one for 61 and one for 62(age).
and for cursors there distinct range will be columns . for example cursor for age 62 should return following as dataset.
user 10-20 21-30 31-40
Count/hour count/hour count/hour
----------------------------------------------
0 5 10 - - - -
1 6 20 8 6 - -
2 7 15 - - - -
5 - - 9 5 - -
7 - - 10 25 - -
10 - - - - 15 30
this column range in temp table is is not a fixed values these are referenced from other table.
edited: i am using PIVOT for above problem, all examples i saw in internet are there for fixed values of column values (range in my case). how can i get dynamic values. following is the ex query:
SELECT *
FROM (SELECT column_2, column_1
FROM test_table)
PIVOT (SUM(column1) AS sum_values FOR (column_2) IN ('value1' AS a, 'value2' AS b, 'value3' AS c));
Instead of using handwritten value i am using following query inside 'IN'
SELECT * from(
with x as (
SELECT DISTINCT range
FROM test_table
WHERE age = 62 )
select ltrim( max( sys_connect_by_path(range, ','))
keep (dense_rank last order by curr),
',') range
from (select range,
row_number() over (order by range) as curr,
row_number() over (order by range) -1 as prev
from x)
connect by prev = PRIOR curr
start with curr = 1 )
it is giving error in this case. But when i using handwritten values its giving right output.
select * from (select user_id, nvl(count,0) count, nvl(hour,0) hour,nvl(range,0) range,nvl(age,0)
age from test_table)
PIVOT (SUM(count) as sum_count, sum(hour) as sum_hour for (range) IN
(
'10-20','21-30','31-40'
)
) where age = 62 order by userid
how can i give values dynamically there?
how can i do it.
Cursors are slow, I would recommend trying to do this in a query unless there's no alternative (or speed doesn't matter). You may want to look into: PIVOT / UNPIVOT which can rotate columns (in this case "range").
Here's some PIVOT / UNPIVOT documentation and examples:
http://www.oracle-developer.net/display.php?id=506
Based on your last edit:
Pretty sure you have two options:
Build dynamic sql based on the distinct values found in the "range" column.
You'll probably be stuck using a cursor again to build the column names but at least it will be limited to just the distinct ranges.
Oracle has a PIVOT XML command that you can use for this.
See: http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html
And scroll down to the section: "XML Type"

Resources