Snowflake - update with correlated subquery using timediff - sql

I am running this query on Snowflake Database:
UPDATE "click" c
SET "Registration_score" =
(SELECT COUNT(*) FROM "trackingpoint" t
WHERE 1=1
AND c."CookieID" = t."CookieID"
AND t."page" ilike '%Registration complete'
AND TIMEDIFF(minute,c."Timestamp",t."Timestamp") < 4320
AND TIMEDIFF(second,c."Timestamp",t."Timestamp") > 0);
The Database returns Unsupported subquery type cannot be evaluated. However, if I run it without the last two conditions (with TIMEDIFF), it works without problem. I confirmed that the actual TIMEDIFF statements are alright with these queries:
select count(*) from "trackingpoint"
where TIMEDIFF(minute, '2018-01-01', "Timestamp") > 604233;
select count(*) from "click"
where TIMEDIFF(minute, '2018-01-01', "Timestamp") > 604233;
and these work without problem. I don't see a reason why the TIMEDIFF condition shoud prevent the database from returning the result. Any idea what should I alter to make it work?

so using the following setup
create table click (id number,
timestamp timestamp_ntz,
cookieid number,
Registration_score number);
create table trackingpoint(id number,
timestamp timestamp_ntz,
cookieid number,
page text );
insert into click values (1,'2018-03-20', 101, 0),
(2,'2019-03-20', 102, 0);
insert into trackingpoint values (1,'2018-03-20 00:00:10', 101, 'user reg comp'),
(2,'2018-03-20 00:00:11', 102, 'user reg comp'),
(3,'2018-03-20 00:00:13', 102, 'pet reg comp'),
(4,'2018-03-20 00:00:15', 102, 'happy dance');
you can see we get the rows we expect
select c.*, t.*
from click c
join trackingpoint t
on c.cookieid = t.cookieid ;
now there are two ways to get your count, the first as you have it, which is good if your counting only one thing, as all the rules are join filtering:
select c.id,
count(1) as new_score
from click c
join trackingpoint t
on c.cookieid = t.cookieid
and t.page ilike '%reg comp'
and TIMEDIFF(minute, c.timestamp, t.timestamp) < 4320
group by 1;
or you can (in snowflake syntax) move the count to the aggregate/select side,and thus get more than one answer if that's what you need (this is the place I find myself more, thus why I present it):
select c.id,
sum(iff(t.page ilike '%reg comp' AND TIMEDIFF(minute, c.timestamp, t.timestamp) < 4320, 1, 0)) as new_score
from click c
join trackingpoint t
on c.cookieid = t.cookieid
group by 1;
thus plugging this into the UPDATE pattern (see last example in the doc's)
https://docs.snowflake.net/manuals/sql-reference/sql/update.html
you can move to a single subselect instead of a corolated subquery which snowflake doesn't support, which is the error message you are getting.
UPDATE click c
SET Registration_score = s.new_score
from (
select ic.id,
count(*) as new_score
from click ic
join trackingpoint it
on ic.cookieid = it.cookieid
and it.page ilike '%reg comp'
and TIMEDIFF(minute, ic.timestamp, it.timestamp) < 4320
group by 1) as s
WHERE c.id = s.id;
The reason add the TIMEDIFF turns your query into a correlated sub-query, is each row of the UPDATE, now relates to the sub-query results, the correlation. The work around is to make "big but simpler" sub-query and join to that.

Related

Oracle SQL re-use subquery "WITH" clause assistance

I have an SQL query in which I need to take the output of a subquery and use it more than once. My existing query works, but only if I repeat the subquery each time I need it. Unfortunately the subquery is complex, and takes time to execute - meaning that multiple iterations really slow the whole thing down.
I have read that you can use the "WITH" statement to assign a subquery output to a variable, in order to re-use that variable. However the problem I'm having is that within the subquery, I need to reference values from the main query. And it appears that if I use WITH - before the main query SELECT - then those references are not recognised. I'll give you a simplified example:
WITH
DateX AS
(
SELECT
MAX(TableSub.Date)
FROM
TableA TableSub
WHERE
TableSub.ID = TableMain.ID
AND TableSub.Event = 'AnotherEvent'
AND TableSub.Date BETWEEN '01-Jan-2015' AND '31-Dec-2015'
)
SELECT
TableMain.ID
FROM
TableA TableMain
WHERE
TableMain.Event = 'MainEvent'
AND TableMain.Date >= DateX
AND (
SELECT
TableSub2.ID
FROM
TableA TableSub2
WHERE
TableSub2.ID = TableMain.ID
TableSub2.Event = 'ThirdEvent'
AND TableSub2.Date <= DateX
) IS NULL
I hope this is clear. It's a simplified version of what I have, but you can see that DateX is used in more than one place: within the main query, and within a subquery. However the problem is that when DateX is defined by WITH, I need to link the ID back to the ID of the main query. And it's not working...
I would be grateful for any advice on this. Am I doing it wrong? Is there a way, or is it just impossible? If so, then should I be using another approach entirely? Thanks.
A better way:
SELECT ID
FROM (
SELECT ID,
"Date",
Event,
LAST_VALUE( CASE Event WHEN 'AnotherEvent' THEN "Date" END IGNORE NULLS )
OVER ( PARTITION BY ID ORDER BY "Date"
ROWS BETWEEN UNBOUNDED PRECEEDING AND UNBOUNDED FOLLOWING
) AS another_date,
FIRST_VALUE( CASE Event WHEN 'ThirdEvent' THEN "Date" END IGNORE NULLS )
OVER ( PARTITION BY ID ORDER BY "Date"
ROWS BETWEEN UNBOUNDED PRECEEDING AND UNBOUNDED FOLLOWING
) AS third_date
FROM TableA
WHERE Event IN ( 'MainEvent', 'ThirdEvent' )
OR ( Event = 'AnotherEvent' AND EXTRACT( YEAR FROM "Date" ) = 2015 )
)
WHERE Event = 'MainEvent'
AND "Date" >= another_date
AND ( third_date IS NULL OR third_date > another_date );
You need to join your DateX CTE on the ID column. Something like:
WITH
DateX AS
(
SELECT
TableSub.ID,
MAX(TableSub.Date) AS MaxDate
FROM
TableA TableSub
WHERE
AND TableSub.Event = 'AnotherEvent'
AND TableSub.Date >= DATE '2015-01-01'
AND TableSub.Date < DATE '2016-01-01'
GROUP BY
TableSub.ID
)
SELECT
TableMain.ID
FROM
TableA TableMain
JOIN
DateX
ON
DateX.ID = TableMain.ID
WHERE
TableMain.Event = 'MainEvent'
AND TableMain.Date >= DateX.MaxDate
AND (
SELECT
TableSub2.ID
FROM
TableA TableSub2
JOIN
DateX
ON
DateX.ID = TableSub2.ID
WHERE
TableSub2.ID = TableMain.ID
TableSub2.Event = 'ThirdEvent'
AND TableSub2.Date <= DateX.MaxDate
) IS NULL
The CTE also needs a column alias for the aggregate; and as you need to join in the ID, you need to include that and group by it.
The last subquery looks odd; you might want NOT EXISTS rather than IS NULL if you're looking for no record. Perhaps your real query is using an aggregate, but even so that might be quicker.
This still may not be the best approach but it's hard to tell from your example. Hitting the same table three times may be unnecessarily expensive.

How to use subquery in Append SQL for Access

I need to add a subquery in my append SQL and it gives me an error:
Query input must contain at least one table or query.
When I replace the subquery with a constant value, no error is returned.
My code is:
INSERT INTO tblActivity ( RequirementReferenceID, ActivityDate, ActivitySource, ActivityTypeID, ActivityDetails, AffectedFieldID )
SELECT [forms]![frmActivity]![UniqueID] AS Expr1,
Now() AS Expr2,
[forms]![frmActivity]![ChangedBy] AS Expr3,
7 AS Expr4,
(Select RequirementStatus from tblStatus
where tblStatus.RequirementStatusID = [forms]![frmActivity]![NewRequirementStatus]) AS Expr5,
48 AS Expr6;
What am I doing wrong?
I found the answer!
Instead of nesting a second Select query inside my first Select query I transformed the first one to reflect what I needed from the second.
INSERT INTO tblActivity ( RequirementReferenceID, ActivityDate, ActivitySource, ActivityTypeID, ActivityDetails, AffectedFieldID )
SELECT [forms]![frmActivity]![UniqueID], Now(), [forms]![frmActivity]![ChangedBy], 7, RequirementStatus, 48
from tblStatus
where tblStatus.RequirementStatusID = [forms]![frmActivity]![NewRequirementStatus];
This works perfectly.

Select Statement Return 0 if Null

I have the following query
SELECT ProgramDate, [CountVal]= COUNT(ProgramDate)
FROM ProgramsTbl
WHERE (Type = 'Type1' AND ProgramDate = '10/18/11' )
GROUP BY ProgramDate
What happens is that if there is no record that matches the Type and ProgramDate, I do not get any records returned.
What I like to have outputted in the above is something like the following if there is no values returned. Notice how for the CountVal we have 0 even if there are no records returned that fit the match condition:
ProgramDate CountVal
10/18/11 0
This is a little more complicated than you would like however, it is very possible. You will first have to create a temporary table of dates. For example, the query below creates a range of dates from 2011-10-11 to 2011-10-20
CREATE TEMPORARY TABLE date_stamps AS
SELECT (date '2011-10-10' + new_number) AS date_stamp
FROM generate_series(1, 10) AS new_number;
Using this temporary table, you can select from it and left join your table ProgramsTbl. For example
SELECT date_stamp,COUNT(ProgramDate)
FROM date_stamps
LEFT JOIN ProgramsTbl ON ProgramsTbl.ProgramDate = date_stamps.date_stamp
WHERE Type = 'Type1'
GROUP BY ProgramDate;
Select ProgramDate, [CountVal]= SUM(occur)
from
(
SELECT ProgramDate, 1 occur
FROM ProgramsTbl
WHERE (Type = 'Type1' AND ProgramDate = '10/18/11' )
UNION
SELECT '10/18/11', 0
)
GROUP BY ProgramDate
Because each SELECT statement is really building a table of records you can use a SELECT query to build a table with both the program count and a default count of zero. This would require two SELECT queries (one to get the actual count, one to get the default count) and using a UNION to combine the two SELECT results into a single table.
From there you can SELECT from the UNIONed table to sum the CountVals (if the programDate occurs in the ProgramTable the CountVal will be
CountVal of the first query if it exists(>0) + CountVal of the second query (=0)).
This way even if there are no records for the desired programDate in ProgramTable you will get a record back indicating a count of 0.
This would look like:
SELECT ProgramDate, SUM(CountVal)
FROM
(SELECT ProgramDate, COUNT(*) AS CountVal
FROM ProgramsTbl
WHERE (Type = 'Type1' AND ProgramDate = '10/18/11' )
UNION
SELECT '10/18/11' AS ProgramDate, 0 AS CountVal) T1
Here's a solution that works on SQL Server; not sure about other db platforms:
DECLARE #Type VARCHAR(5) = 'Type1'
, #ProgramDate DATE = '10/18/2011'
SELECT pt.ProgramDate
, COUNT(pt2.ProgramDate)
FROM ( SELECT #ProgramDate AS ProgramDate
, #Type AS Type
) pt
LEFT JOIN ProgramsTbl pt2 ON pt.Type = pt2.Type
AND pt.ProgramDate = pt2.ProgramDate
GROUP BY pt.ProgramDate
Grunge but simple and efficient
SELECT '10/18/11' as 'Program Date', count(*) as 'count'
FROM ProgramsTbl
WHERE Type = 'Type1' AND ProgramDate = '10/18/11'
Try something along these lines. This will establish a row with a date of 10/18/11 that will definitely return. Then you left join to your actual data to get your desired count (which can now return 0 if there are no corresponding rows).
To do this for more than 1 date, you'd want to build a Date table that holds a list of all dates you want to query (so substitute the "select '10/18/11'" with "select Date from DateTbl").
SELECT ProgDt.ProgDate, [CountVal]= COUNT(ProgramsTbl.ProgramDate)
FROM (SELECT '10/18/11' as 'ProgDate') ProgDt
LEFT JOIN ProgramsTbl
ON ProgDt.ProgDate = ProgramsTbl.ProgramDate
WHERE (Type = 'Type1')
GROUP BY ProgDt.ProgDate
To create a date table that you can use for querying, do this (assumes SQL Server 2005+):
create table Dates (MyDate datetime)
go
insert into Dates
select top 100000 row_number() over (order by s1.name)
from master..spt_values s1, master..spt_values s2
go

#1222 - The used SELECT statements have a different number of columns

Why am i getting a #1222 - The used SELECT statements have a different number of columns
? i am trying to load wall posts from this users friends and his self.
SELECT u.id AS pid, b2.id AS id, b2.message AS message, b2.date AS date FROM
(
(
SELECT b.id AS id, b.pid AS pid, b.message AS message, b.date AS date FROM
wall_posts AS b
JOIN Friends AS f ON f.id = b.pid
WHERE f.buddy_id = '1' AND f.status = 'b'
ORDER BY date DESC
LIMIT 0, 10
)
UNION
(
SELECT * FROM
wall_posts
WHERE pid = '1'
ORDER BY date DESC
LIMIT 0, 10
)
ORDER BY date DESC
LIMIT 0, 10
) AS b2
JOIN Users AS u
ON b2.pid = u.id
WHERE u.banned='0' AND u.email_activated='1'
ORDER BY date DESC
LIMIT 0, 10
The wall_posts table structure looks like id date privacy pid uid message
The Friends table structure looks like Fid id buddy_id invite_up_date status
pid stands for profile id. I am not really sure whats going on.
The first statement in the UNION returns four columns:
SELECT b.id AS id,
b.pid AS pid,
b.message AS message,
b.date AS date
FROM wall_posts AS b
The second one returns six, because the * expands to include all the columns from WALL_POSTS:
SELECT b.id,
b.date,
b.privacy,
b.pid.
b.uid message
FROM wall_posts AS b
The UNION and UNION ALL operators require that:
The same number of columns exist in all the statements that make up the UNION'd query
The data types have to match at each position/column
Use:
FROM ((SELECT b.id AS id,
b.pid AS pid,
b.message AS message,
b.date AS date
FROM wall_posts AS b
JOIN Friends AS f ON f.id = b.pid
WHERE f.buddy_id = '1' AND f.status = 'b'
ORDER BY date DESC
LIMIT 0, 10)
UNION
(SELECT id,
pid,
message,
date
FROM wall_posts
WHERE pid = '1'
ORDER BY date DESC
LIMIT 0, 10))
You're taking the UNION of a 4-column relation (id, pid, message, and date) with a 6-column relation (* = the 6 columns of wall_posts). SQL doesn't let you do that.
(
SELECT b.id AS id, b.pid AS pid, b.message AS message, b.date AS date FROM
wall_posts AS b
JOIN Friends AS f ON f.id = b.pid
WHERE f.buddy_id = '1' AND f.status = 'b'
ORDER BY date DESC
LIMIT 0, 10
)
UNION
(
SELECT id, pid , message , date
FROM
wall_posts
WHERE pid = '1'
ORDER BY date DESC
LIMIT 0, 10
)
You were selecting 4 in the first query and 6 in the second, so match them up.
Beside from the answer given by #omg-ponies; I just want to add that this error also occur in variable assignment. In my case I used an insert; associated with that insert was a trigger. I mistakenly assign different number of fields to different number of variables. Below is my case details.
INSERT INTO tab1 (event, eventTypeID, fromDate, toDate, remarks)
-> SELECT event, eventTypeID,
-> fromDate, toDate, remarks FROM rrp group by trainingCode;
ERROR 1222 (21000): The used SELECT statements have a different number of columns
So you see I got this error by issuing an insert statement instead of union statement. My case difference were
I issued a bulk insert sql
i.e. insert into tab1 (field, ...) as select field, ... from tab2
tab2 had an on insert trigger; this trigger basically decline duplicates
It turns out that I had an error in the trigger. I fetch record based on new input data and assigned them in incorrect number of variables.
DELIMITER ##
DROP TRIGGER trgInsertTrigger ##
CREATE TRIGGER trgInsertTrigger
BEFORE INSERT ON training
FOR EACH ROW
BEGIN
SET #recs = 0;
SET #trgID = 0;
SET #trgDescID = 0;
SET #trgDesc = '';
SET #district = '';
SET #msg = '';
SELECT COUNT(*), t.trainingID, td.trgDescID, td.trgDescName, t.trgDistrictID
INTO #recs, #trgID, #trgDescID, #proj, #trgDesc, #district
from training as t
left join trainingDistrict as tdist on t.trainingID = tdist.trainingID
left join trgDesc as td on t.trgDescID = td.trgDescID
WHERE
t.trgDescID = NEW.trgDescID
AND t.venue = NEW.venue
AND t.fromDate = NEW.fromDate
AND t.toDate = NEW.toDate
AND t.gender = NEW.gender
AND t.totalParticipants = NEW.totalParticipants
AND t.districtIDs = NEW.districtIDs;
IF #recs > 0 THEN
SET #msg = CONCAT('Error: Duplicate Training: previous ID ', CAST(#trgID AS CHAR CHARACTER SET utf8) COLLATE utf8_bin);
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = #msg;
END IF;
END ##
DELIMITER ;
As you can see i am fetching 5 fields but assigning them in 6 var. (My fault totally I forgot to delete the variable after editing.
You are using MySQL Union.
UNION is used to combine the result from multiple SELECT statements into a single result set.
The column names from the first SELECT statement are used as the column names for the results returned. Selected columns listed in corresponding positions of each SELECT statement should have the same data type. (For example, the first column selected by the first statement should have the same type as the first column selected by the other statements.)
Reference: MySQL Union
Your first select statement has 4 columns and second statement has 6 as you said wall_post has 6 column.
You should have same number of column and also in same order in both statement.
otherwise it shows error or wrong data.

Erroneous ORA-01427: single-row subquery returns more than one row

I'm getting the error [ORA-01427: single-row subquery returns more than one row] when I execute a query. I have a query structured like so:
SELECT LV.PRICE,
(SELECT C.MODEL_NAME FROM CARS C WHERE C.MODEL_ID = LV.MODEL_ID) as MODEL_NAME
FROM LEDGER_VIEW LV
WHERE LV.PRICE < 500
It's breaking on the nested select. I know the logic both in the view and in this query is correct, and that there's no chance of the nested select returning more than one row. The CARS table's MODEL_ID is a unique field. If I execute the query without the nested select it doesn't return this error.
The LEDGER_VIEW is a view built on top of another view. Is it possible that these stacked views are buggy in Oracle 10g? I don't know how else to debug this problem.
I am aware I could change this particular query to a join rather than a nested select, but I'd like to know why this is happening because I use nested queries in other places where it is not so easily modifiable.
EDIT: Here's the really strange thing. The LEDGER_VIEW is, as I said, built on top of another view. As a test, I copied the nested view's SQL directly into the SQL of the SQL of LEDGER_VIEW, in place of the nested view, and it returned with no errors (as expected). This seems to confirm to me that there is some buggy behavior either with nested views or with the combination of nested views + database links.
Your subquery is returning multiple rows. Use the query below to find out which MODELID values in the Car table are duplicated:
select MODELID as CarsModelID, count(*) as Count
from cars
where MODELID in (
select MODEL_ID
from LEDGER_VIEW
WHERE LV.PRICE < 500
)
group by MODELID
having count(*) > 1
I am unable to recreate via a creation of a stacked view. (althoug RedFilters will find the culprit)
CREATE TABLE t1
(
t1_id NUMBER ,
txt VARCHAR2( 50 ),
CONSTRAINT t1_pk PRIMARY KEY( t1_id )
) ;
CREATE TABLE t2
(
t2_id NUMBER ,
t1_id NUMBER ,
price NUMBER( 10, 4 ) ,
CONSTRAINT t2_pk PRIMARY KEY( t2_id ),
CONSTRAINT t2_fk FOREIGN KEY( t1_id ) REFERENCES t1( t1_id )
);
insert into t1(t1_id, txt) values(1,'fit');
insert into t1(t1_id, txt) values(2,'focus');
insert into t1(t1_id, txt) values(3,'golf');
insert into t1(t1_id, txt) values(4,'explorer');
insert into t1(t1_id, txt) values(5,'corolla');
insert into t2(t2_id, t1_id, price) values(1,1,17000);
insert into t2(t2_id, t1_id, price) values(2,2,16000);
insert into t2(t2_id, t1_id, price) values(3,3,22000);
insert into t2(t2_id, t1_id, price) values(4,4,31000);
insert into t2(t2_id, t1_id, price) values(5,5,17000);
create view t1_view as select * from t1;
create view t2_view as select * from t2;
create view t_stacked_view as
select t1_view.txt ,
t2_view.price ,
t1_view.t1_id
from t1_view
left join
t2_view
on t1_view.t1_id = t2_view .t1_id
;
--stacked view test
select t1_view.txt ,
(select t_stacked_view.price
from t_stacked_view
where t1_view.t1_id = t_stacked_view .t1_id) price
from t1_view ;
--or better yet, just drop the row level query
select t1_view.txt ,
t2_view.price
from t1_view
left join
t2_view
on t1_view.t1_id = t2_view .t1_id
;
But that begs the question, why are you doing the row level query here? While 10g ought to optimize them the same, I have always found it easier to write queries as below, both for readability, maintainability, and to specifically avoid the error you are having (is it always, 3 years down the road, guaranteed by the application (both in the db and the calling app) that you cannot have a condition that will cause this error? One rouge statement gets in and your entire app dies?
SELECT LV.PRICE,
c.model_name
FROM LEDGER_VIEW LV
LEFT /* OR INNER */ JOIN CARS C
ON C.MODEL_ID = LV.MODEL_ID
WHERE LV.PRICE < 500
I suggest using RedFilter's answer to check whether there are multiple cars with a given MODEL_ID.
If you're absolutely certain that CARS.MODEL_ID is unique, then it implies that the error message is generated by selection from LEDGER_VIEW - so try running the equivalent query without the subquery on CARS, like so:
SELECT LV.PRICE
FROM LEDGER_VIEW LV
WHERE LV.PRICE < 500
If you still see the same error (you should, if CARS.MODEL_ID is unique) you will need to debug LEDGER_VIEW - ie. check for sub-queries returning multiple rows in LEDGER_VIEW and the underlying views it is based on.
Creating views based on views is possible in most forms of SQL, but it is usually a bad idea - for this very reason.
Try forcing your subquery to return a single result by appending rownum = 1, like this:
SELECT LV.PRICE,
(SELECT C.MODEL_NAME FROM CARS C WHERE C.MODEL_ID = LV.MODEL_ID AND ROWNUM = 1) as MODEL_NAME
FROM LEDGER_VIEW LV
WHERE LV.PRICE < 500
It will probably work and if it does, you will know that your subquery returns multiple rows, which judging by the error code it should be. Of course this is not a solution so you might have to fix your data in cars table to actually solve the problem. Leaving and rownum = 1 will eliminate the error if model_id is duplicated again, preventing you from noticing the problem.
select
a.account_number,
a.party_id,
a.TRX_NUMBER,
a.trx_date,
a.order_number,
adv.unapplied_amt,
a.Finance,
a.customer_name,a.PARTY_NAME,
a.customer_number,a.contact_number,
a.name,
a.Aging,
a.transaction_type,
a.exec_name,
a.team_leader,
sum(a.O_SAmount),
(case when (trunc(sysdate) - trunc(a.trx_date)) <=:ag1 then sum(a.O_SAmount) else 0 end ) bucket1,--"<" || :ag1,
(case when (trunc(sysdate) - trunc(a.trx_date)) between :ag1+1 and :ag2 then sum(a.O_SAmount) else 0 end ) bucket2,--:ag1+1 || "to" || :ag2,
(case when (trunc(sysdate) - trunc(a.trx_date)) between :ag2+1 and :ag3 then sum(a.O_SAmount) else 0 end ) bucket3,--:ag2+1 || "to" || :ag3,
(case when (trunc(sysdate) - trunc(a.trx_date)) >:ag3 then sum(a.O_SAmount) else 0 end ) bucket4,
:AS_ON_date
from
(select distinct hca.account_number,hp.party_id,--rcta.CUSTOMER_TRX_ID,
--rcta.trx_number,rcta.trx_date,apsa.due_date,
(
select distinct
--ooha.order_number,
rcta.trx_number
--to_char(rcta.trx_date,'DD-MON-YYYY') trx_date
from
ra_customer_trx_all rcta,
oe_order_headers_all ooh,
oe_order_lines_all oola,
--ra_customer_trx_all rcta,
ra_customer_trx_lines_all rctla,
ra_cust_trx_types_all rctta
--ra_customer_trx_lines_all rctl
where 1=1
AND ooh.header_id = oola.header_id
--AND ooh.order_number = '111111010101698'
AND ooh.order_number=oohA.order_number
AND TO_CHAR (ooh.order_number) = rcta.ct_reference
AND rcta.customer_trx_id = rctla.customer_trx_id
AND rctla.inventory_item_id = oola.inventory_item_id
and rcta.CUST_TRX_TYPE_ID = rctta.cust_trx_type_id
and rcta.org_id = rctta.org_id
and rctta.type like 'INV'
and oola.ordered_item LIKE 'MV%'
AND oola.attribute3 = 'Y'
AND ooh.flow_status_code <> 'ENTERED'
AND oola.flow_status_code <> 'CANCELLED'
)TRX_NUMBER,
(select distinct
--ooha.order_number,
--rcta.trx_number
rcta.trx_date
from
ra_customer_trx_all rcta,
oe_order_headers_all ooh,
oe_order_lines_all oola,
--ra_customer_trx_all rcta,
ra_customer_trx_lines_all rctla,
ra_cust_trx_types_all rctta
--ra_customer_trx_lines_all rctl
where 1=1
AND ooh.header_id = oola.header_id
--AND ooh.order_number = '111111010101698'
AND ooh.order_number=oohA.order_number
AND TO_CHAR (ooh.order_number) = rcta.ct_reference
AND rcta.customer_trx_id = rctla.customer_trx_id
AND rctla.inventory_item_id = oola.inventory_item_id
and rcta.CUST_TRX_TYPE_ID = rctta.cust_trx_type_id
and rcta.org_id = rctta.org_id
and rctta.type like 'INV'
and oola.ordered_item LIKE 'MV%'
AND oola.attribute3 = 'Y'
AND ooh.flow_status_code <> 'ENTERED'
AND oola.flow_status_code <> 'CANCELLED'
)TRX_Date,
rcta.INTERFACE_HEADER_ATTRIBUTE1 order_number,
ooha.attribute10 Finance,
f.customer_name,HP.PARTY_NAME,
TO_NUMBER(f.customer_number)customer_number,hp.primary_phone_number contact_number,--csi.incident_number,
--cii.instance_number,
haou.name,
--sum(acr.amount) Advance,--rcta.CUST_TRX_TYPE_ID,--acr.cash_receipt_id,
--sum(abs((apsa.AMOUNT_DUE_REMAINING-nvl(acr.amount,0)))) "O_SAmount",
apsa.AMOUNT_DUE_REMAINING O_SAmount,
--sum(abs((apsa.AMOUNT_DUE_REMAINING))) "O_SAmount",
round(months_between(sysdate,rcta.trx_date)*30) Aging,
--(case when ((round(months_between(sysdate,rcta.trx_date)*30)>=0) or (round(months_between(sysdate,rcta.trx_date)*30)<:aging1)) then apsa.AMOUNT_DUE_REMAINING end) "0 TO 30"
--(case when (trunc(sysdate) - trunc(apsa.Due_Date)) <=:ag1 then apsa.AMOUNT_DUE_REMAINING else 0 end ) bucket1,--"<" || :ag1,
--(case when (trunc(sysdate) - trunc(apsa.Due_Date)) between :ag1+1 and :ag2 then apsa.AMOUNT_DUE_REMAINING else 0 end ) bucket2,--:ag1+1 || "to" || :ag2,
--(case when (trunc(sysdate) - trunc(apsa.Due_Date)) between :ag2+1 and :ag3 then apsa.AMOUNT_DUE_REMAINING else 0 end ) bucket3,--:ag2+1 || "to" || :ag3,
--(case when (trunc(sysdate) - trunc(apsa.Due_Date)) >:ag3 then apsa.AMOUNT_DUE_REMAINING else 0 end ) bucket4,
--apsa.amount_due_original,
--TO_NUMBER(apsa.AMOUNT_DUE_REMAINING)AMOUNT_DUE_REMAINING,
rctta.name transaction_type,
PAPF.full_name||'-'||PAPF.EMPLOYEE_NUMBER exec_name,
ooha.attribute9 team_leader,
:AS_ON_date
from ra_customer_trx_all rcta,
oe_order_headers_all ooha,
hz_cust_accounts hca,
hz_parties hp,
--cs_incidents_all_b csi,
--csi_item_instances cii,
hr_all_organization_units haou,
ar_cash_receipts_all acr,
ar_receivable_applications_all aaa,
ra_cust_trx_types_all RCTTA,
hr.per_all_people_f papf,
ar_customers f,
ar_payment_schedules_all apsa,
jtf.JTF_RS_SALESREPS jrs
where 1=1
--and INTERFACE_HEADER_ATTRIBUTE1 like '111111060100538'
--and INTERFACE_HEADER_ATTRIBUTE1 like '111111010105402'
--and INTERFACE_HEADER_ATTRIBUTE1 like '111111010102791'
and rcta.ct_reference(+)=TO_CHAR(ooha.order_number)
AND f.customer_id = (rcta.bill_to_customer_id)
and f.customer_id=hca.cust_account_id
and hca.party_id=hp.party_id
and haou.organization_id=rcta.INTERFACE_HEADER_ATTRIBUTE10
--and hp.party_id=cii.owner_party_id
--and csi.inventory_item_id=cii.inventory_item_id
--and csi.inv_organization_id=haou.organization_id
--and haou.organization_id=nvl(:location,haou.organization_id)
and ooha.SHIP_FROM_ORG_ID=nvl(:location,haou.organization_id)
AND RCTTA.NAME like :transaction_type||'%'
--decode(:org_id,null,null,(select name from ar_cash_receipts_all where organization_id = :org_id)) ||'%')
and rcta.trx_date<=to_date(:AS_ON_date)
--AND RCTTA.NAME=NVL(:TRANS_TYPE,RCTTA.NAME)
and rcta.org_id=nvl(:org_id,rcta.org_id)
--and f.customer_name like 'VIKAS SATAV'
and aaa.applied_customer_trx_id(+)=rcta.customer_trx_id
and aaa.cash_receipt_id=acr.cash_receipt_id(+)
and rcta.status_trx like 'OP'
and rcta.CUST_TRX_TYPE_ID=rctta.CUST_TRX_TYPE_ID
and apsa.CUSTOMER_TRX_ID=rcta.CUSTOMER_TRX_ID
and TO_NUMBER(apsa.AMOUNT_DUE_REMAINING) >0
--and hp.party_id=papf.party_id(+)
and jrs.salesrep_id = ooha.SALESREP_ID
and jrs.ORG_ID = ooha.ORG_ID
and jrs.PERSON_ID = papf.PERSON_ID(+)
) a,
(
select
b.order_number,
sum(b.AMOUNT_APPLIED) unapplied_amt
from
(select distinct to_char(ooha.order_number) order_number,ara.* from
oe_order_headers_all ooha,
oe_payments oe,
ar_receivable_applications_all ara
where 1=1--ooha.order_number = :p_order_num
and oe.header_id=ooha.header_id
and ara.PAYMENT_SET_ID=oe.PAYMENT_SET_ID
and ara.DISPLAY='Y'
and (ara.STATUS like 'OTHER ACC' or ara.STATUS like 'UNAPP') --or ara.STATUS like 'ACC')
) b
group by b.order_number
) adv
where adv.order_number(+)=a.order_number
group by a.account_number,
a.party_id,
a.TRX_NUMBER,
a.trx_date,
a.order_number,
adv.unapplied_amt,
a.Finance,
a.customer_name,a.PARTY_NAME,
a.customer_number,a.contact_number,
a.name,
a.Aging,
a.transaction_type,
a.exec_name,
a.team_leader
order by a.Aging desc