Tuesday, December 30, 2014

CONNECT BY

There are two mandatory keywords to build a hierarchy, CONNECT BYand PRIOR. A hierarchy is built when one row is the parent of another row. START WITHdefines the first ancestor.
SELECT
   ENAME
FROM
   EMP
CONNECT BY
   PRIOR EMPNO = MGR
START WITH
   ENAME = 'JONES';
ENAME
----------
JONES
SCOTT
ADAMS
FORD
SMITH
Jones and his employees are returned. Adams is an employee of Scott and Scott is an employee of Jones so Adams is also returned. 
The pseudo-column level returns the depth of the hierarchy. The first level is the root:
SELECT
   ENAME
FROM
   EMP
WHERE
   LEVEL=2
CONNECT BY
   PRIOR EMPNO = MGR
START WITH
   ENAME = 'JONES';
ENAME
--------
SCOTT
FORD
Only the direct employees of Jones are returned. Jones is the first ancestor and has a level of 1. Adams and Smith are one level below the direct employees and belong to the third level started by Jones.
The tree is displayed with the children indented under their parents by using padding with a number of spaces proportional to LEVEL.
SELECT
   CONCAT
   (
      LPAD
      (
         ' ',
         LEVEL*3-3
      ),
      ENAME
   ) ENAME
FROM
   EMP
CONNECT BY
   PRIOR EMPNO = MGR
START WITH
   MGR IS NULL;
ENAME
------------------
KING
   JONES
      SCOTT
         ADAMS
      FORD
         SMITH
   BLAKE
      ALLEN
      WARD
      MARTIN
      TURNER
      JAMES
   CLARK
      MILLER
Starting with the top manager, the names of the employees are padded with white spaces according to their level.
The rows in a hierarchical query are returned as a tree, the children following the parent. ORDER SIBLINGS BYpreserves the hierarchy and orders the children of each parent.
SELECT
   CONCAT
   (
      LPAD
      (
         ' ',
         LEVEL*3-3
      ),
      ENAME
   ) ENAME
FROM
   EMP
CONNECT BY
   PRIOR EMPNO = MGR
START WITH
   MGR IS NULL
ORDER SIBLINGS BY
   EMP.ENAME;
ENAME
----------------
KING
   BLAKE
      ALLEN
      JAMES
      MARTIN
      TURNER
      WARD
   CLARK
      MILLER
   JONES
      FORD
         SMITH
      SCOTT
         ADAMS
Clark comes after Blake and before Jones; they are under King and ordered by their name. Their children are sorted and the hierarchical appearance is preserved.
ORDER BYwithout SIBLINGSdestroys the hierarchy:
SELECT
   CONCAT
   (
      LPAD
      (
         ' ',
         LEVEL*3-3
      ),
      ENAME
   ) ENAME
FROM
   EMP
CONNECT BY
   PRIOR EMPNO = MGR
START WITH
   MGR IS NULL
ORDER BY
   EMP.ENAME;
ENAME
--------------
         ADAMS
      ALLEN
   BLAKE
   CLARK
      FORD
      JAMES
   JONES
KING
      MARTIN
      MILLER
      SCOTT
         SMITH
      TURNER
      WARD

Some Complex quries

1) How to delete duplicate records
A) delete from emp where rowid != (select max(rowid) from emp where group by empno);
==========================================================================================================
2) update the salary with avg sal of the employee whoes salary is less than avg salary of their own dept.

update emp a set sal = (select avg(sal) from emp b where a.deptno = b.deptno)
where sal < (select avg(sal) from emp c where  c.deptno = b.deptno);
==========================================================================================================
3) N th  Max sal record

    1)select * from (select rownum R,sal S (select distinct sal s from emp order by sal desc)) where R = &no;
  if you want records then --
    2)select * from emp where rowid in
 ( select a from ( select  rowid a, dense_rank()  over (order by sal desc) r ,sal from (select sal from emp order by sal desc) ) where r = &N)

     3)select max(sal) ,level from emp where level = &n  connect by prior sal>sal GROUP by level;
==========================================================================================================   
4) list of top 5 salaries

select * from (select rownum R,sal S (select distinct sal s from emp order by sal desc)) where R <=5;
==========================================================================================================
5)3 rd max/min sal

select a.sal from emp a where 3=(select count(*)  from emp b where a.sal<=b.sal);
select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2 where e1.sal <= e2.sal);
select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2where e1.sal >= e2.sal);
===========================================================================================================
6)select max sal of each dept

select deptno ,max(sal) from emp group by deptno;   
===========================================================================================================
7) fetch alternative records in table(even)

select * from emp where rowid in (select decode( mod(rownum,2) ,0 ,rowid ,null) from emp)

8)fetch alternative records in table(odd)

select * from emp where rowid in (select decode( mod(rownum,2) ,0 ,null,rowid) from emp)

9) last n records

select * from emp minus
(select * from emp where ronum <=
(select count(*)-&n from emp ))

10) Select all records where dept no of both emp and dept table matches.
select * from emp where exists(select * from dept where emp.deptno=dept.deptno)

11)If there are two tables emp1 and emp2, and both have common record. How can I fetch all the recods but common records only once?
(Select * from emp) Union (Select * from emp1)

12)How to fetch only common records from two tables emp and emp1?
(Select * from emp) Intersect (Select * from emp1)

13) How can I retrive all records of emp1 those should not present in emp2?
(Select * from emp) Minus (Select * from emp1)

14)Count the total sal  deptno wise where more than 2 employees exist.
SELECT  deptno, sum(sal) As totalsal
FROM emp
GROUP BY deptno
HAVING COUNT(empno) > 2

15) select second highest salry of each deptno.

select max(sal) from emp a
where sal < (select max(sal) from emp b where a.deptno = b.deptno)
group by deptno;


Monday, December 29, 2014

EMP table data

EMP table data

DDL:-
=========================
create table dept(
  deptno number(2,0),
  dname  varchar2(14),
  loc    varchar2(13),
  constraint pk_dept primary key (deptno)
);
 
create table emp(
  empno    number(4,0),
  ename    varchar2(10),
  job      varchar2(9),
  mgr      number(4,0),
  hiredate date,
  sal      number(7,2),
  comm     number(7,2),
  deptno   number(2,0),
  constraint pk_emp primary key (empno),
  constraint fk_deptno foreign key (deptno) references dept (deptno)
);
 
DML:-
 
============================
insert into dept
values(10, 'ACCOUNTING', 'NEW YORK');
insert into dept
values(20, 'RESEARCH', 'DALLAS');
insert into dept
values(30, 'SALES', 'CHICAGO');
insert into dept
values(40, 'OPERATIONS', 'BOSTON');

insert into emp
values(
 7839, 'KING', 'PRESIDENT', null,
 to_date('17-11-1981','dd-mm-yyyy'),
 5000, null, 10
);
insert into emp
values(
 7698, 'BLAKE', 'MANAGER', 7839,
 to_date('1-5-1981','dd-mm-yyyy'),
 2850, null, 30
);
insert into emp
values(
 7782, 'CLARK', 'MANAGER', 7839,
 to_date('9-6-1981','dd-mm-yyyy'),
 2450, null, 10
);
insert into emp
values(
 7566, 'JONES', 'MANAGER', 7839,
 to_date('2-4-1981','dd-mm-yyyy'),
 2975, null, 20
);
insert into emp
values(
 7788, 'SCOTT', 'ANALYST', 7566,
 to_date('13-JUL-87','dd-mm-rr') - 85,
 3000, null, 20
);
insert into emp
values(
 7902, 'FORD', 'ANALYST', 7566,
 to_date('3-12-1981','dd-mm-yyyy'),
 3000, null, 20
);
insert into emp
values(
 7369, 'SMITH', 'CLERK', 7902,
 to_date('17-12-1980','dd-mm-yyyy'),
 800, null, 20
);
insert into emp
values(
 7499, 'ALLEN', 'SALESMAN', 7698,
 to_date('20-2-1981','dd-mm-yyyy'),
 1600, 300, 30
);
insert into emp
values(
 7521, 'WARD', 'SALESMAN', 7698,
 to_date('22-2-1981','dd-mm-yyyy'),
 1250, 500, 30
);
insert into emp
values(
 7654, 'MARTIN', 'SALESMAN', 7698,
 to_date('28-9-1981','dd-mm-yyyy'),
 1250, 1400, 30
);
insert into emp
values(
 7844, 'TURNER', 'SALESMAN', 7698,
 to_date('8-9-1981','dd-mm-yyyy'),
 1500, 0, 30
);
insert into emp
values(
 7876, 'ADAMS', 'CLERK', 7788,
 to_date('13-JUL-87', 'dd-mm-rr') - 51,
 1100, null, 20
);
insert into emp
values(
 7900, 'JAMES', 'CLERK', 7698,
 to_date('3-12-1981','dd-mm-yyyy'),
 950, null, 30
);
insert into emp
values(
 7934, 'MILLER', 'CLERK', 7782,
 to_date('23-1-1982','dd-mm-yyyy'),
 1300, null, 10
);

Tuesday, November 25, 2014

PO quries

=====================================
Concurrent Program Runtime in Minutes
=====================================
SELECT
  /*+ rule */
  rq.request_id "Req. ID",
  tl.user_concurrent_program_name "Program Name",
  to_char(rq.actual_start_date,'DD-MON-YY HH24:MI:SS') "Start Date",
  to_char(rq.actual_completion_date,'DD-MON-YY HH24:MI:SS') "Completion Date",
  ROUND((rq.actual_completion_date - rq.actual_start_date) * 1440, 2) "Runtime (in Minutes)"
FROM apps.fnd_concurrent_programs_tl tl,
  apps.fnd_concurrent_requests rq
WHERE tl.application_id             = rq.program_application_id
AND tl.concurrent_program_id        = rq.concurrent_program_id
AND tl.LANGUAGE                     = USERENV('LANG')
AND rq.actual_start_date           IS NOT NULL
AND rq.actual_completion_date      IS NOT NULL
AND tl.user_concurrent_program_name = 'Journal Import' -- <change it>
ORDER BY rq.request_id DESC;

=======================================
Purchase Order from Requisition Number
=======================================

This is the query to find out the purchase order number from requisition number

SELECT DISTINCT pha.segment1
FROM po_headers_all pha,
  po_distributions_all pda,
  po_req_distributions_all rda,
  po_requisition_headers_all rha,
  po_requisition_lines_all rla
WHERE pha.po_header_id       =pda.po_header_id
AND pda.req_distribution_id  =rda.distribution_id
AND rda.requisition_line_id  =rla.requisition_line_id
AND rla.requisition_header_id=rha.requisition_header_id
AND rha.segment1             ='&Requisition'

You can also find out the requisition number from purchase order number by using query given below

SELECT DISTINCT rha.segment1
FROM apps.po_requisition_headers_all rha,
  apps.po_requisition_lines_all rla,
  apps.po_req_distributions_all rda,
  apps.po_distributions_all pda,
  apps.po_headers_all pha
WHERE rha.requisition_header_id=rla.requisition_header_id
AND rla.requisition_line_id    =rda.requisition_line_id
AND rda.distribution_id        =pda.req_distribution_id
AND pda.po_header_id           =pha.po_header_id
AND pha.segment1               ='626900'

Friday, October 31, 2014

Complete Order to Cash(O2C) Techno-Functional flow in R12

Complete Order to Cash(O2C) Techno-Functional flow in R12




Order to Cash Cycle in Brief:
The Order to Cash Process flow starts with entering the order with a standard item into system. When you enter an order, the item are validated in oracle inventory, the price is calculated for the items using the pricing engine; the availability of the items are checked and may be reserved. Once all the required fields are entered on both the header and the lines, you can book the order. When you click on the Book Order button, the API OEXUBOKB.pls, checks if the order is eligible for booking. If eligible the order is booked and the order header status would change to booked. The next step is the pick release with which you move the items from the warehouse to the staging area. The next step is to ship confirm, to indicate that the items are loaded on to the carrier from the staging area. When you run Ship Confirm, the system decrements inventory and updates sales order line status. This information is then transferred through the Auto Invoice to Account Receivables for invoicing. Then you sent the invoice to your customer for the items shipped and then perform the cash management and bank reconciliations.
Order Management receives detailed item information from the Inventory application and price list information from the Pricing application. Orders and returns can be entered manually or imported through an EDI, CRM, or external source. Once in the system the order is ready to be pick released and shipped, if needed by the Shipping application. It can then proceed through the Auto Invoice program into the Oracle Receivables application to be invoiced. All of the accounting information is transferred to the General Ledger by the Inventory and Receivables applications.
The required fields to enter on the sales order header are the customer name or number and order type. Other values such as Ship-To Address, Bill-To Address, Shipping Method, and Price List default. The order number is generated based on the order type. The required fields to enter on the sales order lines are Ordered Item and Quantity. Again, based on defaulting rules and setups in Pricing, Inventory and Shipping, the other values would default on the sales order line.

Setup steps for executing the Order to Cash flow with a standard item:
·         Prior to order entry, the items should be created / defined in inventory module using the master items screen and assigned to the shipping organization. Check the blog post for the related setups
·         Add the item to the price list or create a new price list.
·         Transaction Type must be defined
·         Document Sequence must be assigned to the document category.
·         Customers must be defined
·         Salespersons must be defined
·         Shipping Roles should be granted to the user.
·         Ensure that the items are available in your shipping sub inventory or perform miscellaneous transactions to augment the same.

Following are some useful related links:
Check the blog post for tables involved in various stages of O2C
Check the blog post on queries involved in Order management
Order to Cash flow with tables involved in various stages:


Order to Cash flow with statuses at various stages:


All possible flow statuses of the order/line:
• OE_ORDER_HEADERS_ALL.flow_status_code: Order Header (Entered) Ã Booked Order (Booked) Ã  Closed Order (Closed)

• OE_ORDER_LINES_ALL.flow_status_code: Order Line (Entered) Ã  Booked Order (Awaiting Shipping) Ã  Pick Released(Picked/Staged) Ã  Ship Confirmed (Shipped) Ã  INV/OM interfaced (Fulfilled)à Close Order (Closed)
1.    Enter the order header, line details and Book it:
Responsibility: Order Management Super User, Vision Operations (USA)
Navigate to Orders, Returns Ã  Sales Orders
Open the Sales Orders Window

Order Number: 66413


  
2.    Schedule order:
·         Check if the order lines are scheduled or not. If any of the order line is in BOOKED status, it means that the order line is not yet scheduled.

·         Run the Schedule Order concurrent program to schedule the order. After the concurrent program is scheduled the order line will move to Awaiting Shipping status.

·         Still if the order lines do not go to Awaiting Shipping, check for any holds on the order line/ header. Release the holds (if any) and re-run theSchedule Order program.
·         You can even schedule the order line in the following way: Right click on the order line and progress the line to schedule it. Check the OM scheduling related setups

Order tables:
OE_ORDER_LINES_ALL.visible_demand_flag: visible_demand_flag= Yes lines will be made available as Demanded to Planning

Shipping tables: The shipping tables get populated after order scheduling.
WSH_DELIVERY_DETAILS.released_status: monitors the shipping process of the order line

WSH_DELIVERY_ASSIGNMENTS: Assigns delivery details to a delivery and/or a parent delivery detail.

Once the order is booked from the application, following changes occur in the backend
§  OE_ORDER_HEADERS_ALL (flow_status_code as BOOKED, booked_flag updated to Y)
§  OE_ORDER_LINES_ALL (flow_status_code as AWAITING_SHIPPING, booked_flag updated Y)
§  Since the order is now booked, delivery details of the order are created in WSH_DELIVERY_DETAILS table. WSH_DELIVERY_DETAILS has delivery lines and LPNs.
                           OOL.line_id = WDD.source_line_id
§  These delivery details information can been viewed form ‘Shipping Transactions Form’ and the delivery status in the application will be as ‘Ready to Release’
§  WSH_DELIVERY_DETAILS.released_status =’R’
§  WSH_DELIVERY_DETAILS.Release_Status can have any of the below valid values
§  WSH_DELIVERY_ASSIGNMENTS (WDA) assigns delivery details to a delivery and/or a parent delivery detail (LPN).

WDA.delivery_detail_id = WDD.delivery_detail_id

§  WSH_DELIVERY_ASSIGNMENTS.delivery_id will be NULL as still pick release operation is not performed as final delivery is not yet created.
§  At the same time when order is booked ‘Demand interface program’ is triggered in the background and demand of the item with specified quantity is created and these demand information is stored in MTL_DEMAND.
MTL_DEMAND.demand_source_line = OOL.line_id

3.    Pick Release the Sales Order
·         Navigate to the Shipping Transaction Form (Shipping Ã  Transactions)
Enter the following in the Query Manager window and click Find
From Order Number = 66413 To Order Number = 66413

·         You can find the data in Shipping transaction screen (WSH shipping tables) only when order is scheduled.

·         On the Shipping Transaction Form select Launch Pick Release from the Action menu and click on GO button. 

·         If Auto Pick confirm is not selected while pick release, then we have to manually do the transact move order process. In fact pick confirm also triggers the transact move order process in which the inventory is moved from item sub inventory to staging area.

Order line status becomes ‘Picked’ on Order and ‘Staged/Pick Confirmed’ on Shipping Form.

§  MTL_MATERIAL_TRANSACTIONS_TEMP (Record gets deleted from here and gets posted to MTL_MATERIAL_TRANSACTIONS)
§  OE_ORDER_LINES_ALL.flow_status_code =’PICKED’
§  MTL_MATERIAL_TRANSACTIONS is updated with Sales Order Pick Transaction 

MMT.trx_source_line_id  = OOL.line_id

§  MTL_TRANSACTION_ACCOUNTS is updated with accounting information
§  WSH_DELIVERY_DETAILS. released_status=‘Y’ (‘Released’)
§  WSH_DELIVERY_ASSIGNMENTS, MTL_ONHAND_QUANTITIES are updated accordingly
Note: Pick Confirm step can be eliminated if ‘Auto Pick Confirm’ is selected as ‘YES’ while performed manual pick release. If Pick release is done through shipping transactions form and if you want to perform auto pick confirm then picking rules setup has to be done.
4.    Ship Confirm the Sales Order
·         Navigate to the Shipping Transaction Form (Shipping Ã   Transactions)

·         Enter the following in the Query Manager window and click Find
From Order Number = 66413 To Order Number = 66413

·         On the Shipping Transaction Form navigate to the Delivery Tab and select Ship Confirm from the Action menu and click on GO button. Ship confirm process triggers the Interface Trip Stops concurrent program.

o    OE_ORDER_LINES_ALL.flow_status_code =‘SHIPPED’
o    WSH_DELIVERY_DETAILS. released_status=‘C’ (‘Shipped’)
o    Data from MTL_TRANSACTIONS_INTERFACE is moved to MTL_MATERIAL_TRANACTIONS and MTL_MATERIAL_TRANSACTIONS is updated withSales Order Issue transaction.
o    Data is deleted from MTL_DEMAND, MTL_RESERVATIONS and WSH_NEW_DELIVERIES
o    Item reduced from MTL_ONHAND_QUANTITIES
MTL_TRANSACTION_ACCOUNTS is updated with accounting information.

Following are the pick release status:
Table: WSH_DELIVERY_DETAILS
Column: RELEASED_STATUS
Possible Values:
B: Backordered- Line failed to be allocated in Inventory
C: Shipped -Line has been shipped
D: Cancelled -Line is Cancelled
N: Not Ready for Release -Line is not ready to be released
R: Ready to Release: Line is ready to be released
S: Released to Warehouse: Line has been released to Inventory for processing
X: Not Applicable- Line is not applicable for Pick Release
Y: Staged- Line has been picked and staged by Inventory


Check the blog post for the detailed pick release status



  
·         Verify the details on the Confirm Delivery window and click OK and close the window.  
5.    Run the Interface Trip Stop – SRS Program
·         The Interface Trip Stop (ITS) will be trigger at the time of Shipping if check box “Defer Interface” is not check. ITS can also be executed from concurrent request.

Interface Trip Stop has two main components:
1.    Update the Order Management Data (oe_order_lines_all)
2.    Trigger the Inventory Interface (to Update the Inventory tables)

·         ITS updates the following fields on oe_order_lines_all table:
·         Shipped_quantity
·         Shipping_quantity
·         Actual_shipment_date

·         Inventory Interface will be trigger only if the first part, that means related to OM has successfully completed and flag OE_INTERFACED_FLAG = ‘Y’ on WSH_DELIVERY_DETAILS.  If value of this flag is N/P then Inventory Interface will never be triggered. And even if you try to submit the Inventory Interface from SRS, delivery detail with oe_interfaced_flag =’N’ will never be picked up.

o    oe_interfaced_flag = Y -- signifies ITS has interfaced shipping data to OM
o    inv_interfaced_flag = Y -- signifies ITS has interfaced shipping data to INV

Navigate to Shipping Interfaces window (Shipping 
à Interfaces Ã  Run)
Select the Interface Trip Stop - SRS Program from the LOVs
On the parameters window enter
Mode = All
Click on the OK button and then on the Submit button:

6.    Run the Master AutoInvoice Program
Navigate to the Run AutoInvoice window, (Interfaces Ã  AutoInvoice)
Select the AutoInvoice Master Program from the LOV
On the parameters window enter
Invoice Source = ORDER ENTRY
Default Date = Enter Today’s Date
(Low) Sales Order Number = 66413
(High) Sales Order Number = 66413
Then click OK and Submit button.

7.    View the Transaction created by the AutoInvoice Program
·         Navigate to the Additional Line Information window, (Orders, Returns Ã Order Organizer)
·         On the Find Order window, query your order number = 66413
·         On the Order Organizer window, navigate to Lines Tab and click on Actions button and select the Additional Line information and click OK.

8.    On the Additional Line Information window, navigate to Invoices / Credit Memos Tab and click on the Invoice Details button. This would open Transactions window, where you can see the invoice details.

Following is an important Query which gives the joining between OMWSHAR Tables
SELECT ooh.order_number
              ,ool.line_id
              ,ool.ordered_quantity
              ,ool.shipped_quantity
              ,ool.invoiced_quantity
              ,wdd.delivery_detail_id
              ,wnd.delivery_id
              ,rctl.interface_line_attribute1
              ,rctl.interface_line_attribute3
              ,rctl.interface_line_attribute6
              ,rct.org_id
              ,rct.creation_date
              ,trx_number
              ,rctl.quantity_ordered
              ,rct.interface_header_context
  FROM oe_order_headers_all ooh
             ,oe_order_lines_all ool
             ,wsh_delivery_details wdd
             ,wsh_new_deliveries wnd
             ,wsh_delivery_assignments wda
             ,ra_customer_trx_all rct
             ,ra_customer_trx_lines_all rctl
 WHERE ooh.header_Id=ool.header_id
      AND wdd.source_header_id=ooh.header_id
      AND wdd.delivery_detail_Id=wda.delivery_detail_id
      AND wda.delivery_id=wnd.delivery_id
      AND rctl.interface_line_attribute1=to_char(ooh.order_number)
      AND rctl.interface_line_attribute6=to_char(ool.line_id)
      AND rctl.interface_line_attribute3=to_char(wnd.delivery_id)
      AND rctl.customer_trx_id=rct.customer_trx_id
      AND rct.interface_header_context='ORDER ENTRY'


O2C: Accounting Entries:

Transaction Event
Debit
Credit
Module
Enter Sales Order
No Accounting Entry
Order Mgmt
Book Order
Pick Release Order
Ship goods to customer
Cost of Goods Sold a/c
Inventory a/c
Inventory
Issue Invoice
Receivables a/c
Revenue a/c
Receivables
Collecting Payment
Cash/Bank a/c
Receivables a/c
Receivables

Useful Queries for Checking Concurrent Requests and Programs

Useful Queries for Checking Concurrent Requests and Programs

Hi DBAs,
As an Apps DBA we have to monitor the Concurrent jobs status and details frequently,This can be done with the help of the below queries.

-- Concurrent Program Queries for Apps DBA:

-- Query 1:For checking the locks in concurrent jobs 

SELECT DECODE(request,0,'Holder: ','Waiter: ')||sid sess,inst_id,id1, id2, lmode, request, type FROM gV$LOCK
WHERE (id1, id2, type) IN (SELECT id1, id2, type FROM gV$LOCK WHERE request>0) ORDER BY id1,request;

-- Query 2:For checking the concurrent programs running currently with Details of Processed time-- and Start Date

 SELECT DISTINCT c.USER_CONCURRENT_PROGRAM_NAME,round(((sysdate-a.actual_start_date)*24*60*60/60),2) AS Process_time,
 a.request_id,a.parent_request_id,a.request_date,a.actual_start_date,a.actual_completion_date,(a.actual_completion_date-a.request_date)*24*60*60 AS end_to_end,
 (a.actual_start_date-a.request_date)*24*60*60 AS lag_time,d.user_name, a.phase_code,a.status_code,a.argument_text,a.priority
FROM   apps.fnd_concurrent_requests a,apps.fnd_concurrent_programs b,apps.FND_CONCURRENT_PROGRAMS_TL c,apps.fnd_user d
WHERE  a.concurrent_program_id=b.concurrent_program_id AND b.concurrent_program_id=c.concurrent_program_id AND
a.requested_by=d.user_id AND status_code='R' order by Process_time desc;
   
-- Query 3:For checking last run of a Concurrent Program along with Processed time
-- Useful to find the Details of Concurrent programs which run daily and comparison purpose

SELECT DISTINCT c.USER_CONCURRENT_PROGRAM_NAME,
            round(((a.actual_completion_date-a.actual_start_date)*24*60*60/60),2) AS Process_time,
            a.request_id,a.parent_request_id,To_Char(a.request_date,'DD-MON-YY HH24:MI:SS'),To_Char(a.actual_start_date,'DD-MON-YY HH24:MI:SS'),
  To_Char(a.actual_completion_date,'DD-MON-YY HH24:MI:SS'), (a.actual_completion_date-a.request_date)*24*60*60 AS end_to_end,
            (a.actual_start_date-a.request_date)*24*60*60 AS lag_time,
            d.user_name, a.phase_code,a.status_code,a.argument_text,a.priority
FROM   apps.fnd_concurrent_requests a,
            apps.fnd_concurrent_programs b ,
            apps.FND_CONCURRENT_PROGRAMS_TL c,
            apps.fnd_user d
WHERE       a.concurrent_program_id= b.concurrent_program_id AND
            b.concurrent_program_id=c.concurrent_program_id AND
            a.requested_by =d.user_id AND
--          trunc(a.actual_completion_date) = '24-AUG-2005'
c.USER_CONCURRENT_PROGRAM_NAME='Incentive Compensation Analytics - ODI' --  and argument_text like  '%, , , , ,%';
--          and status_code!='C'

-- Query 4:For Checking the last run of concurrent Program.
- Use below query to check all the concurrent request running which may refer given package
-- This is very useful check before compiling any package on given instance.
-- The query can be modified as per requirement.
-- Remove FND_CONCURRENT_REQUESTS table and joins to check all program dependent on given package.

SELECT
 FCR.REQUEST_ID
,FCPV.USER_CONCURRENT_PROGRAM_NAME
,FCPV.CONCURRENT_PROGRAM_NAME
,FCPV.CONCURRENT_PROGRAM_ID
,FCR.STATUS_CODE
,FCR.PHASE_CODE
FROM FND_CONCURRENT_PROGRAMS_VL FCPV
,FND_EXECUTABLES FE
,SYS.DBA_DEPENDENCIES DD
,FND_CONCURRENT_REQUESTS FCR
WHERE FCPV.EXECUTABLE_ID = FE.EXECUTABLE_ID
AND FE.EXECUTION_METHOD_CODE = 'I'
AND SUBSTR(FE.EXECUTION_FILE_NAME,1,INSTR(FE.EXECUTION_FILE_NAME, '.', 1, 1) - 1) = UPPER(DD.NAME)
AND DD.REFERENCED_TYPE IN ('VIEW', 'TABLE', 'TRIGGER', 'PACKAGE') -- add as required
--AND referenced_owner = 'XXCUS'
AND DD.REFERENCED_NAME = UPPER('&Package_name')
AND FCR.CONCURRENT_PROGRAM_ID = FCPV.CONCURRENT_PROGRAM_ID
AND fcr.phase_code NOT IN ( 'C','P');

-- Query 5:The following query will display the time taken to execute the concurrent Programs
--for a particular user with the latest concurrent programs sorted in least time taken 
-- to complete the request. 

 SELECT
      f.request_id ,
      pt.user_concurrent_program_name user_conc_program_name,
      f.actual_start_date start_on,
      f.actual_completion_date end_on,
      floor(((f.actual_completion_date-f.actual_start_date)
        *24*60*60)/3600)
        || ' HOURS ' ||
        floor((((f.actual_completion_date-f.actual_start_date)
        *24*60*60) -
        floor(((f.actual_completion_date-f.actual_start_date)
        *24*60*60)/3600)*3600)/60)
        || ' MINUTES ' ||
        round((((f.actual_completion_date-f.actual_start_date)
        *24*60*60) -
        floor(((f.actual_completion_date-f.actual_start_date)
        *24*60*60)/3600)*3600 -
        (floor((((f.actual_completion_date-f.actual_start_date)
        *24*60*60) -
        floor(((f.actual_completion_date-f.actual_start_date)
        *24*60*60)/3600)*3600)/60)*60) ))
        || ' SECS ' time_difference,
      p.concurrent_program_name concurrent_program_name,
      decode(f.phase_code,'R','Running','C','Complete',f.phase_code) Phase,
      f.status_code
from  apps.fnd_concurrent_programs p,
      apps.fnd_concurrent_programs_tl pt,
      apps.fnd_concurrent_requests f
where f.concurrent_program_id = p.concurrent_program_id
      and f.program_application_id = p.application_id
      and f.concurrent_program_id = pt.concurrent_program_id
      and f.program_application_id = pt.application_id
      AND pt.language = USERENV('Lang')
      and f.actual_start_date is not null
order by
      f.actual_start_date desc;

--Query 6: By using the below Query we can get sid,serial#,spid of the concurrent Request..
   
    SELECT a.request_id, d.sid, d.serial# , c.SPID
    FROM apps.fnd_concurrent_requests a,
    apps.fnd_concurrent_processes b,
    v$process c,
    v$session d
    WHERE a.controlling_manager = b.concurrent_process_id
    AND c.pid = b.oracle_process_id
    AND b.session_id=d.audsid
    AND a.request_id = &Request_ID
    AND a.phase_code = 'R';

--Query 7: By using below Concurrent Manager and Program rules...
--Gives Detail of the Concurrent_queue_name and User_concurrent_program_name

SELECT b.concurrent_queue_name, c.user_concurrent_program_name
FROM FND_CONCURRENT_QUEUE_CONTENT a, fnd_concurrent_queues b, fnd_concurrent_programs_vl c
WHERE a.queue_application_id = 283
and a.concurrent_queue_id = b.concurrent_queue_id
and a.type_id = c.concurrent_program_id
order by decode(INCLUDE_FLAG, 'I', 1, 2), type_code;
   
--Query 8: Gives Details of Running Concurrent jobs

SELECT DISTINCT c.USER_CONCURRENT_PROGRAM_NAME,
      round(((sysdate-a.actual_start_date)*24*60*60/60),2) AS Process_time,
    a.request_id,a.parent_request_id,a.request_date,a.actual_start_date,a.actual_completion_date,
      (a.actual_completion_date-a.request_date)*24*60*60 AS end_to_end,
      (a.actual_start_date-a.request_date)*24*60*60 AS lag_time,
      d.user_name, a.phase_code,a.status_code,a.argument_text,a.priority
FROM     apps.fnd_concurrent_requests a,
    apps.fnd_concurrent_programs b ,
    apps.FND_CONCURRENT_PROGRAMS_TL c,
    apps.fnd_user d
WHERE   a.concurrent_program_id=b.concurrent_program_id AND
    b.concurrent_program_id=c.concurrent_program_id AND
    a.requested_by=d.user_id AND
    status_code='R' order by Process_time desc;
   
 -- Query 9: Gives detail of Concurrent job completed and pending

SELECT
 FCR.REQUEST_ID
,FCPV.USER_CONCURRENT_PROGRAM_NAME
,FCPV.CONCURRENT_PROGRAM_NAME
,FCPV.CONCURRENT_PROGRAM_ID
,FCR.STATUS_CODE
,FCR.PHASE_CODE
FROM FND_CONCURRENT_PROGRAMS_VL FCPV
,FND_EXECUTABLES FE
,SYS.DBA_DEPENDENCIES DD
,FND_CONCURRENT_REQUESTS FCR
WHERE FCPV.EXECUTABLE_ID = FE.EXECUTABLE_ID
AND FE.EXECUTION_METHOD_CODE = 'I'
AND SUBSTR(FE.EXECUTION_FILE_NAME,1,INSTR(FE.EXECUTION_FILE_NAME, '.', 1, 1) - 1) = UPPER(DD.NAME)
AND DD.REFERENCED_TYPE IN ('VIEW', 'TABLE', 'TRIGGER', 'PACKAGE') -- add as required
--AND referenced_owner = 'XXCUS'
AND DD.REFERENCED_NAME = UPPER('&Package_name')
AND FCR.CONCURRENT_PROGRAM_ID = FCPV.CONCURRENT_PROGRAM_ID
AND fcr.phase_code NOT IN ( 'C','P');

-- Query 10:Gives Detail of Running and Completed Concurrent jobs with Start date and end date 
-- Latest one at the top

select
      f.request_id ,
      pt.user_concurrent_program_name user_conc_program_name,
      f.actual_start_date start_on,
      f.actual_completion_date end_on,
      floor(((f.actual_completion_date-f.actual_start_date)
        *24*60*60)/3600)
        || ' HOURS ' ||
        floor((((f.actual_completion_date-f.actual_start_date)
        *24*60*60) -
        floor(((f.actual_completion_date-f.actual_start_date)
        *24*60*60)/3600)*3600)/60)
        || ' MINUTES ' ||
        round((((f.actual_completion_date-f.actual_start_date)
        *24*60*60) -
        floor(((f.actual_completion_date-f.actual_start_date)
        *24*60*60)/3600)*3600 -
        (floor((((f.actual_completion_date-f.actual_start_date)
        *24*60*60) -
        floor(((f.actual_completion_date-f.actual_start_date)
        *24*60*60)/3600)*3600)/60)*60) ))
        || ' SECS ' time_difference,
      p.concurrent_program_name concurrent_program_name,
      decode(f.phase_code,'R','Running','C','Complete',f.phase_code) Phase,
      f.status_code
from  apps.fnd_concurrent_programs p,
      apps.fnd_concurrent_programs_tl pt,
      apps.fnd_concurrent_requests f
where f.concurrent_program_id = p.concurrent_program_id
      and f.program_application_id = p.application_id
      and f.concurrent_program_id = pt.concurrent_program_id
      and f.program_application_id = pt.application_id
      AND pt.language = USERENV('Lang')
      and f.actual_start_date is not null
order by
      f.actual_start_date desc;

--- Query 11 wait events details related with Concurrent programs

SELECT s.saddr, s.SID, s.serial#, s.audsid, s.paddr, s.user#, s.username,
s.command, s.ownerid, s.taddr, s.lockwait, s.status, s.server,
s.schema#, s.schemaname, s.osuser, s.process, s.machine, s.terminal,
UPPER (s.program) program, s.TYPE, s.sql_address, s.sql_hash_value,
s.sql_id, s.sql_child_number, s.sql_exec_start, s.sql_exec_id,
s.prev_sql_addr, s.prev_hash_value, s.prev_sql_id,
s.prev_child_number, s.prev_exec_start, s.prev_exec_id,
s.plsql_entry_object_id, s.plsql_entry_subprogram_id,
s.plsql_object_id, s.plsql_subprogram_id, s.module, s.module_hash,
s.action, s.action_hash, s.client_info, s.fixed_table_sequence,
s.row_wait_obj#, s.row_wait_file#, s.row_wait_block#,
s.row_wait_row#, s.logon_time, s.last_call_et, s.pdml_enabled,
s.failover_type, s.failover_method, s.failed_over,
s.resource_consumer_group, s.pdml_status, s.pddl_status, s.pq_status,
s.current_queue_duration, s.client_identifier,
s.blocking_session_status, s.blocking_instance, s.blocking_session,
s.seq#, s.event#, s.event, s.p1text, s.p1, s.p1raw, s.p2text, s.p2,
s.p2raw, s.p3text, s.p3, s.p3raw, s.wait_class_id, s.wait_class#,
s.wait_class, s.wait_time, s.seconds_in_wait, s.state,
s.wait_time_micro, s.time_remaining_micro,
s.time_since_last_wait_micro, s.service_name, s.sql_trace,
s.sql_trace_waits, s.sql_trace_binds, s.sql_trace_plan_stats,
s.session_edition_id, s.creator_addr, s.creator_serial#
FROM v$session s
WHERE ( (s.username IS NOT NULL)
AND (NVL (s.osuser, 'x') <> 'SYSTEM')
AND (s.TYPE <> 'BACKGROUND') AND STATUS='ACTIVE'
)
ORDER BY "PROGRAM";

-- Query 12 To find the pid of the Concurrent job and kill it.

Select a.inst_id, sid, b.spid
from gv$session a, gv$process b,apps.fnd_concurrent_requests c where a.paddr = b.addr and request_ID ='31689665' 
AND a.inst_id = b.inst_id and c.os_process_id = a.process;

-- Query 13:To find the Database SID of the Concurrent job
-- We need our concurrent request ID as an input.
-- c.SPID= is the operating system process id
-- d.sid= is the Oracle process id

SQL> column process heading "FNDLIBR PID"
SELECT a.request_id, d.sid, d.serial# ,d.osuser,d.process , c.SPID
FROM apps.fnd_concurrent_requests a,
apps.fnd_concurrent_processes b,
v$process c,
v$session d
WHERE a.controlling_manager = b.concurrent_process_id
AND c.pid = b.oracle_process_id
AND b.session_id=d.audsid
AND a.request_id = &Request_ID
AND a.phase_code = 'R';


-- Query 14:To find the currently running SQL after finding SID from Query 12

SELECT SQL_TEXT FROM V$SQLAREA WHERE (ADDRESS, HASH_VALUE) IN
(SELECT SQL_ADDRESS, SQL_HASH_VALUE FROM V$SESSION WHERE SID=11710);

-- Query 15:To find what exactly the program,module and the SQL it is executing
--P2 column should change that means Concurrent program is changing blocks and moving

select sid,serial#,p2,program,module from gv$session where sid=11710;

-- Query 16:To find any blocking is there in RAC or non-RAC Database

select process,sid,blocking_session,BLOCKING_INSTANCE from gv$session
where blocking_session is not null;

-- Query17:To check the SID and concurrent program details, where 5991=SID

select sid,serial#,program,module,p2 from gv$session where SID=5991;

-- Query 18: To check time remaining in minutes and elapsed  in minutes for long running job 

Select round(sofar*100/totalwork,2)"finished(%)",
Sid,
Serial#,
Opname,
Target,
Sofar,
Totalwork,
Units,
(Time_Remaining/60) Time_Rem_Mins,
(Elapsed_Seconds/60) Elapsed_Time_Mins
From gV$session_Longops
where TIME_REMAINING>0;

--Query 19:To get the location of the trace file for Concurrent request id,eg:The Request ID --(205979614)  
SELECT 'Request id: '||request_id ,
'Trace id: '||oracle_Process_id,
'Trace Flag: '||req.enable_trace,
'Trace Name:
'||dest.value||'/'||lower(dbnm.value)||'_ora_'||oracle_process_id||'.trc',
'Prog. Name: '||prog.user_concurrent_program_name,
'File Name: '||execname.execution_file_name|| execname.subroutine_name ,
'Status : '||decode(phase_code,'R','Running')
||'-'||decode(status_code,'R','Normal'),
'SID Serial: '||ses.sid||','|| ses.serial#,
'Module : '||ses.module
from fnd_concurrent_requests req, v$session ses, v$process proc,
v$parameter dest, v$parameter dbnm, fnd_concurrent_programs_vl prog,
fnd_executables execname
where req.request_id = &request
and req.oracle_process_id=proc.spid(+)
and proc.addr = ses.paddr(+)
and dest.name='user_dump_dest'
and dbnm.name='db_name'
and req.concurrent_program_id = prog.concurrent_program_id
and req.program_application_id = prog.application_id
--- and prog.application_id = execname.application_id
and prog.executable_application_id = execname.application_id
and prog.executable_id=execname.executable_id;

Note:We can use the above query to diagnose the Concurrent job failure by enabling trace on that job first and than running that concurrent job again.

--Query 20:To list the concurrent programs that run today,Giving details about status and logs

SELECT DISTINCT fcp.user_concurrent_program_name,
                fcp.concurrent_program_name,
                fcr.request_id,
                fcr.request_date,
                flv.meaning status,
                fcr.status_code,
                fcr.completion_text,
                fcr.logfile_name,
                fcr.outfile_name,
                fcr.argument_text
  FROM apps.fnd_concurrent_programs_vl fcp,
       apps.fnd_concurrent_requests    fcr,
       apps.fnd_lookup_values          flv
 WHERE fcr.concurrent_program_id = fcp.concurrent_program_id
   AND trunc(fcr.last_update_date) = trunc(SYSDATE)
   AND flv.lookup_code = fcr.status_code
   AND flv.lookup_type = 'CP_STATUS_CODE'
   AND flv.language = 'US'
 ORDER BY fcr.request_date,
          fcr.request_id DESC;