oracle : joining subquery with outer query - oracle

I have two queries with a union as follows:
select '00/00/0000' as payment_date , h1.customer_no
from payments h1
where not exists ( select 1 from payments h2 where h2.customer_no = h1.customer_no and h2.ctype = 'CASH' )
and h1.customer_no = 400
group by h1.customer_no
union
select to_char(h1.payment_date, 'MM/DD/YYYY') , h1.customer_no
from payments h1 inner join ( select customer_no, max(payment_date ) as max_date from payments where ctype = 'CASH' group by customer_no ) subQ
on ( h1.customer_no = subQ.customer_no
and h1.payment_date = subQ.max_date )
and h1.customer_no = 400
group by h1.payment_date, h1.customer_no
Now, I want to use this union in another query.
select * from (
select '00/00/0000' as payment_date , h1.customer_no
from payments h1
where not exists ( select 1 from payments h2 where h2.customer_no = h1.customer_no and h2.ctype = 'CASH' )
and h1.customer_no = p.customer_no
group by h1.customer_no
union
select to_char(h1.payment_date, 'MM/DD/YYYY') , h1.customer_no
from payments h1 inner join ( select customer_no, max(payment_date ) as max_date from payments where ctype = 'CASH' group by customer_no ) subQ
on ( h1.customer_no = subQ.customer_no
and h1.payment_date = subQ.max_date )
and h1.customer_no = p.customer_no
group by h1.payment_date, h1.customer_no ) sq,
payments p
where p.customer_no = 400
and sq.customer_no = p.customer_no
when I run this, I get ORA-00904: "P"."CUSTOMER_NO": invalid identifier. I need to join h1.customer_no to outer queries customer_no.
I have seen some queries with rank but I couldn't quite figure it out. How do I join the inner query with the outer query?
thanks in advance.

Does your payments table have a customer_no column? That seems to be what your error is indicating.
As for how to join the subqueries, you might want to look into factored subqueries. You can do:
WITH z AS (
SELECT ...
UNION
SELECT ...
), y AS (
SELECT ...
)
SELECT ...
FROM y
JOIN z ON y.x = z.x
JOIN some_other_table t ON z.a = t.a

Related

Oracle Hierarchical queries: Translate START WITH ... CONNECT BY PRIOR into 'Recursive Subquery Factoring'

How would the following START WITH / CONNECT BY hierarchical query look like when translated into a RECURSIVE SUBQUERY FACTORING hierarchical query with WITH clause:
SELECT t1.id
FROM table1 t1, table2 t2
WHERE t1.version_id = t2.id
AND t1.baseline_date = TRIM (TO_DATE ('2015-05-26', 'yyyy-mm-dd'))
AND t2.entry_date = t1.baseline_date
START WITH t1.id IN (SELECT id
FROM table1
WHERE parent_id = 101015)
CONNECT BY PRIOR t1.id = t1.parent_id
ORDER SIBLINGS BY t1.child_index;
I think you want:
WITH rsqfc (id, child_index, baseline_date) AS (
SELECT t1.id,
t1.child_index,
t1.baseline_date
FROM table1 t1
INNER JOIN table2 t2
ON ( t1.version_id = t2.id
AND t2.entry_date = t1.baseline_date )
WHERE t1.parent_id = 101015
UNION ALL
SELECT t1.id,
t1.child_index,
t1.baseline_date
FROM rsqfc r
INNER JOIN table1 t1
ON (r.id = t1.parent_id)
INNER JOIN table2 t2
ON ( t1.version_id = t2.id
AND t2.entry_date = t1.baseline_date )
)
SEARCH DEPTH FIRST BY child_index SET order_id
SELECT id
FROM rsqfc
WHERE baseline_date = DATE '2015-05-26';
However, without sample data it is difficult to be sure.

Why can't a query using 2 CTEs be linked to another table [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have something similar to the code below. I'm new to Oracle. It works fine until I try to join it to "anothertable" then states it can't see cte2.a. I can't find anything that explains why it can't see cte2.a
I need the data created by cte2 to further my query. Should i just do that inside of cte2 instead?
WITH cte 1 as (......),
cte2 as (....join tablename on tablename.x = cte1.x)
select *
from cte2
join anothertable on anothertable.a = cte2.a
Here is the actual query. It states "MAX_HEM"."PATIENT_ID": invalid identifier
WITH HGB AS(
SELECT DISTINCT
PH.PATIENT_ID,
PH.HEMATOLOGY_CD, --EX HGB
PH.PATIENT_HEMATOLOGY_ID,
PH.HEMATOLOGY_RESULT,
PH.TRANSACTION_DATE,
PH.TRANSACTION_TIME,
(TO_CHAR(PH.TRANSACTION_DATE) || ' ' || (TO_CHAR(TO_DATE(LPAD(PH.TRANSACTION_TIME,4,'0'),'HH24MI'),'HH:MI AM'))) AS HGB_DATETIME,
TO_NUMBER(TRIM(LEADING 0 FROM(TO_CHAR(ORDER_PRODUCT_INVENTORY.ISSUE_DATETIME,'HH24MI')))) AS ISSUE_TIME,
ORDER_PRODUCT_INVENTORY.ISSUE_DATETIME || ' ' || (TO_CHAR(ORDER_PRODUCT_INVENTORY.ISSUE_DATETIME, 'HH:MI AM')) AS ISSUE_DTTM,
PRODUCT_INVENTORY.UNIT_NO,
CD_TRANSACTION.WTCODE
FROM
PRODUCT_INVENTORY_ACTIVITY PRODUCT_INVENTORY_ACTIVITY
JOIN CD_TRANSACTION CD_TRANSACTION ON PRODUCT_INVENTORY_ACTIVITY.TRANSACTION_CD = CD_TRANSACTION.TRANSACTION_CD
AND (CD_TRANSACTION.WTCODE='TA' OR CD_TRANSACTION.WTCODE='TX' OR CD_TRANSACTION.WTCODE='IE')
JOIN ORDER_PRODUCT_INVENTORY ORDER_PRODUCT_INVENTORY ON PRODUCT_INVENTORY_ACTIVITY.PRODINV_ID = ORDER_PRODUCT_INVENTORY.PRODINV_ID
JOIN ORDERS ORDERS ON ORDER_PRODUCT_INVENTORY.ORDER_ID = ORDERS.ORDER_ID
JOIN PATIENT_HEMATOLOGY PH ON PH.PATIENT_ID = ORDERS.PATIENT_ID
JOIN CD_ORDER_PRODUCT_INV_STAT CD_ORDER_PRODUCT_INV_STAT ON ORDER_PRODUCT_INVENTORY.ORDER_PRODUCT_INV_STAT_CD = CD_ORDER_PRODUCT_INV_STAT.ORDER_PRODUCT_INV_STAT_CD
JOIN PRODUCT_INVENTORY PRODUCT_INVENTORY ON ORDER_PRODUCT_INVENTORY.PRODINV_ID = PRODUCT_INVENTORY.PRODINV_ID
WHERE PH.HEMATOLOGY_CD = 'HGB'
AND PH.TRANSACTION_DATE <= TRUNC(ORDER_PRODUCT_INVENTORY.ISSUE_DATETIME)
AND PH.TRANSACTION_TIME <= TO_NUMBER(TRIM(LEADING 0 FROM(TO_CHAR(ORDER_PRODUCT_INVENTORY.ISSUE_DATETIME,'HH24MI'))))
AND CD_ORDER_PRODUCT_INV_STAT.WTCODE='TRANSFUSED'
AND (CD_TRANSACTION.WTCODE='TA' OR CD_TRANSACTION.WTCODE='TX' OR CD_TRANSACTION.WTCODE='IE')
AND ORDER_PRODUCT_INVENTORY.ISSUE_DATETIME IS NOT NULL
AND (ORDER_PRODUCT_INVENTORY.ISSUE_DATETIME>=TO_DATE ('01-09-2020 00:00:00', 'DD-MM-YYYY HH24:MI:SS')
AND ORDER_PRODUCT_INVENTORY.ISSUE_DATETIME<TO_DATE ('06-09-2020 00:00:00', 'DD-MM-YYYY HH24:MI:SS'))
ORDER BY PH.PATIENT_ID, UNIT_NO,TO_DATE(PH.TRANSACTION_DATE) DESC, PH.TRANSACTION_TIME DESC
),
MAX_HEM AS
(
SELECT
HGB.PATIENT_ID "PatID",
MAX(HGB.PATIENT_HEMATOLOGY_ID) "HemID",
MAX(HGB.TRANSACTION_DATE) "TransDate",
MAX(HGB.TRANSACTION_TIME) "TransTime",
MAX(HGB.HEMATOLOGY_RESULT) "HGB_Results",
MAX(HGB.UNIT_NO) "UnitNo"
FROM PATIENT_HEMATOLOGY PH1
LEFT JOIN HGB ON PH1.PATIENT_ID = HGB.PATIENT_ID
GROUP BY HGB.PATIENT_ID
ORDER BY HGB.PATIENT_ID
)
select
HGB.*,
MAXHEM.*
FROM MAX_HEM
LEFT JOIN ORDERS ORDERS ON ORDERS.PATIENT_ID = MAX_HEM.PATIENT_ID
I tried the below and its working for me. Just check is it something like this you are expecting?
WITH cte AS
( select 'a' as a from dual
union
select 'g' as a from dual
), cte2 AS
(select 'a' as b from dual
union
select 'c' as b from dual
)
SELECT *
FROM cte c inner JOIN cte2 c2 ON c.a = c2.b
Your query works:
WITH cte1 (x) as (
SELECT dummy FROM DUAL
),
cte2 (x, a) as (
SELECT tablename.x,
tablename.a
FROM cte1
join tablename
on tablename.x = cte1.x
)
select *
from cte2
join anothertable
on anothertable.a = cte2.a;
Which, for the sample data:
CREATE TABLE tablename ( x, a ) AS
SELECT dummy, ROWNUM FROM DUAL;
CREATE TABLE anothertable ( a ) AS
SELECT ROWNUM FROM DUAL;
Outputs:
X | A | A
:- | -: | -:
X | 1 | 1
db<>fiddle here

Oracle Optimize Query at View

I have Query at view which is make the cost so heavy:
CREATE OR REPLACE FORCE EDITIONABLE VIEW "TMI_ISD_WV_LINK_REV4" ("P_DATA_NO", "DATA_KR_NO", "R_DATA_NO", "R_WF_ST", "SYSTEM_MATTER_ID") AS
SELECT wvl."P_DATA_NO"
,wvl."DATA_KR_NO"
,wvl."R_DATA_NO"
,wvl."R_WF_ST"
,(
select system_matter_id from (select system_matter_id from TMI_ISD_ALL_WORKFLOW wfl WHERE wfl.DATA_NO IN (wvl.R_DATA_NO,wvl.P_DATA_NO) order by wfl.create_date_TIME desc )
where rownum <= 1--fetch first 1 row only
)SYSTEM_MATTER_ID
FROM TMI_ISD_WV_LINK_REV3 wvl;
The max cost taken by this View :
TMI_ISD_WV_LINK_REV3 and TMI_ISD_ALL_WORKFLOW is also View:
CREATE OR REPLACE FORCE EDITIONABLE VIEW "TMI_ISD_ALL_WORKFLOW" ("KS_CD", "DATA_NO", "SYSTEM_MATTER_ID", "USER_DATA_ID", "MATTER_NUMBER", "FLOW_ID", "KI_WF_ST", "PROCESS_DATE", "APPLY_AUTH_USER_CODE", "CREATE_DATE_TIME", "CREATER_ID", "UPDATE_DATE_TIME", "UPDATER_ID") AS
SELECT "KS_CD","DATA_NO","SYSTEM_MATTER_ID","USER_DATA_ID","MATTER_NUMBER","FLOW_ID","KI_WF_ST","PROCESS_DATE","APPLY_AUTH_USER_CODE","CREATE_DATE_TIME","CREATER_ID","UPDATE_DATE_TIME","UPDATER_ID"
FROM NWA7_WF_HZ_KGH_KSH_SS
UNION ALL
SELECT "KS_CD","DATA_NO","SYSTEM_MATTER_ID","USER_DATA_ID","MATTER_NUMBER","FLOW_ID","KI_WF_ST","PROCESS_DATE","APPLY_AUTH_USER_CODE","CREATE_DATE_TIME","CREATER_ID","UPDATE_DATE_TIME","UPDATER_ID"
FROM NWA7_WF_HZ_KGH_KSH_YT
union all
SELECT "KS_CD","DATA_NO","SYSTEM_MATTER_ID","USER_DATA_ID","MATTER_NUMBER","FLOW_ID","KI_WF_ST","PROCESS_DATE","APPLY_AUTH_USER_CODE","CREATE_DATE_TIME","CREATER_ID","UPDATE_DATE_TIME","UPDATER_ID"
FROM NWA7_WF_HZ_SCRH_SS
UNION ALL
SELECT "KS_CD","DATA_NO","SYSTEM_MATTER_ID","USER_DATA_ID","MATTER_NUMBER","FLOW_ID","KI_WF_ST","PROCESS_DATE","APPLY_AUTH_USER_CODE","CREATE_DATE_TIME","CREATER_ID","UPDATE_DATE_TIME","UPDATER_ID"
FROM NWA7_WF_HZ_SC_YT
UNION ALL
SELECT "KS_CD","DATA_NO","SYSTEM_MATTER_ID","USER_DATA_ID","MATTER_NUMBER","FLOW_ID","KI_WF_ST","PROCESS_DATE","APPLY_AUTH_USER_CODE","CREATE_DATE_TIME","CREATER_ID","UPDATE_DATE_TIME","UPDATER_ID"
FROM NWA7_WF_HZ_SKH_YT
UNION ALL
SELECT "KS_CD","DATA_NO","SYSTEM_MATTER_ID","USER_DATA_ID","MATTER_NUMBER","FLOW_ID","KI_WF_ST","PROCESS_DATE","APPLY_AUTH_USER_CODE","CREATE_DATE_TIME","CREATER_ID","UPDATE_DATE_TIME","UPDATER_ID"
FROM NWA7_WF_HZ_SKH_SS;
TMI_ISD_WV_LINK_REV3 :
CREATE OR REPLACE FORCE EDITIONABLE VIEW "TMI_ISD_WV_LINK_REV3" ("P_DATA_NO", "DATA_KR_NO", "R_DATA_NO", "R_WF_ST", "SYSTEM_MATTER_ID") AS
SELECT J1.data_no AS P_DATA_NO
,J1.data_kr_no
,J2.data_no AS R_DATA_NO
,J2.KI_WF_ST AS R_WF_ST
,J3.SYSTEM_MATTER_ID
FROM NWJ2_T_KGH_KSH_YT_HZ J1
LEFT JOIN (
SELECT a.KS_CD
,a.DATA_KR_NO
,a.DATA_NO
,b.KI_WF_ST
FROM NWJ2_T_KGH_KSH_SS_HZ a
JOIN NWA8_T_KS_SK_KGH_KSH_SS b ON a.KS_CD = b.KS_CD
AND a.DATA_NO = b.DATA_NO
WHERE a.KGH_KSH_SS_YK_KBN = '1'
) J2 ON J1.KS_CD = J2.KS_CD
AND J1.DATA_KR_NO = J2.DATA_KR_NO
LEFT JOIN (
SELECT KS_CD,SYSTEM_MATTER_ID,DATA_NO
FROM NWA7_WF_HZ_KGH_KSH_SS
UNION ALL
SELECT KS_CD,SYSTEM_MATTER_ID,DATA_NO
FROM NWA7_WF_HZ_KGH_KSH_YT
) J3 ON J1.KS_CD = J3.KS_CD
AND J1.DATA_NO = J3.DATA_NO
WHERE J1.KGH_KSH_YT_YK_KBN = '1'
UNION ALL
SELECT B1.data_no AS P_DATA_NO
,B1.data_kr_no
,B2.data_no AS R_DATA_NO
,B2.KI_WF_ST AS R_WF_ST
,B3.SYSTEM_MATTER_ID
FROM NWB2_T_SC_YT_HZ B1
LEFT JOIN (
SELECT a.KS_CD
,a.DATA_KR_NO
,a.DATA_NO
,b.KI_WF_ST
FROM NWB2_T_SC_RH_SS_HZ a
JOIN NWA8_T_KS_SK_SCRH_SS b ON a.KS_CD = b.KS_CD
AND a.DATA_NO = b.DATA_NO
WHERE a.SC_RH_SS_YK_KBN = '1'
) B2 ON B1.DATA_KR_NO = B2.DATA_KR_NO
AND B1.KS_CD = B2.KS_CD
LEFT JOIN (
SELECT KS_CD,SYSTEM_MATTER_ID,DATA_NO
FROM NWA7_WF_HZ_SCRH_SS
UNION ALL
SELECT KS_CD,SYSTEM_MATTER_ID,DATA_NO
FROM NWA7_WF_HZ_SC_YT
) B3 ON B1.KS_CD = B3.KS_CD
AND B1.DATA_NO = B3.DATA_NO
WHERE B1.SC_YT_YK_KBN = '1'
UNION ALL
SELECT C1.data_no AS P_DATA_NO
,C1.DATA_KR_NO
,C2.data_no AS R_DATA_NO
,C2.KI_WF_ST AS R_WF_ST
,C3.SYSTEM_MATTER_ID
FROM NWC2_T_SKH_YT_HZ C1
LEFT JOIN (
SELECT a.KS_CD
,a.DATA_KR_NO
,a.DATA_NO
,b.KI_WF_ST
FROM NWC2_T_SKH_SS_HZ a
JOIN NWA8_T_KS_SK_SKH_SS b ON a.KS_CD = b.KS_CD
AND a.DATA_NO = b.DATA_NO
WHERE a.SKH_SS_YK_KBN = '1'
) C2 ON C1.DATA_KR_NO = C2.DATA_KR_NO
AND C1.KS_CD = C2.KS_CD
LEFT JOIN (
SELECT KS_CD,SYSTEM_MATTER_ID,DATA_NO
FROM NWA7_WF_HZ_SKH_YT
UNION ALL
SELECT KS_CD,SYSTEM_MATTER_ID,DATA_NO
FROM NWA7_WF_HZ_SKH_SS
) C3 ON C1.KS_CD = C3.KS_CD
AND C1.DATA_NO = C3.DATA_NO
WHERE C1.SKH_YT_YK_KBN = '1';
As far as i know, I can not add index from view at oracle, so I am guessing the culprit is this sub query at TMI_ISD_WV_LINK_REV4:
(
select system_matter_id from (select system_matter_id from TMI_ISD_ALL_WORKFLOW wfl WHERE wfl.DATA_NO IN (wvl.R_DATA_NO,wvl.P_DATA_NO) order by wfl.create_date_TIME desc )
where rownum <= 1--fetch first 1 row only
)SYSTEM_MATTER_ID
Actually this performance has been tuned up using Materialized View, but the data will updated every 3 minutes once, or like that.
Thank You all.

Sql recursive error invalid column name CTE

I have done following CTE it works fine,but I need to get sum of the last node so the problem is when I add T1.Debit Column to be calculated its give me an invalid column name 'Debit' !!! on line ***
ALTER Function [dbo].[SubTopics_GetSum]
-- Add the parameters for the stored procedure here
(
#TopicID int
)
RETURNS TABLE
AS
RETURN
(
-- Add the SELECT statement with parameter references here
WITH cte
AS (
SELECT
T1.TopicID,
T1.Code,
T1.Description,
T1.ParentID,
T1.ParentID AS NewParentID,
CAST(T1.Code AS nvarchar(MAX)) AS TopicCode,
CAST(T1.Description AS nvarchar(MAX)) AS TopicDescription,
isnull((Accounting.DocumentDetail.Debit),0) AS Debit,
isnull((Accounting.DocumentDetail.Credit),0) AS Credit
FROM Accounting.Topics AS T1
LEFT OUTER JOIN Accounting.DocumentDetail
ON T1.TopicID = Accounting.DocumentDetail.TopicFK
where NOT EXISTS(
SELECT
T2.TopicID,
T2.Code,
T2.Description,
T2.ParentID,
isnull((Accounting.DocumentDetail.Debit),0) AS Debit,
isnull((Accounting.DocumentDetail.Credit),0) AS Credit
FROM Accounting.Topics AS T2
LEFT OUTER JOIN Accounting.DocumentDetail
ON T2.TopicID = Accounting.DocumentDetail.TopicFK
WHERE (ParentID = T1.TopicID)
)
UNION ALL
SELECT
c.TopicID,
c.Code,
c.Description,
c.ParentID,
T1.ParentID AS NewParentID,
CAST(T1.Code AS nvarchar(MAX)) + c.TopicCode AS TopicCode,
CAST(T1.Description AS nvarchar(MAX)) + ' - ' + c.TopicDescription AS TopicDescription,
*** isnull((T1.Debit),0)+isnull(c.Debit,0) AS Debit,--IN THIS LINE error 'Invalid Column Name 'Debit''
isnull(c.Credit,0) AS Credit
FROM cte AS c
INNER JOIN Accounting.Topics AS T1
ON T1.TopicID = c.NewParentID
)
SELECT isnull(sum(Debit),0)AS Debit,
isnull(sum(Credit),0)AS Credit
FROM cte AS c
WHERE (NewParentID = #TopicID)
)
let me know whats wrong with my code confused !!!
actually it doesn't return me a last node sum of debit,credit ... !!!
check following pic
I think below code will help,
ALTER FUNCTION [dbo].[Subtopics_getsum]
-- Add the parameters for the stored procedure here
(#TopicID INT)
returns TABLE
AS
RETURN (
-- Add the SELECT statement with parameter references here
WITH cte
AS (SELECT T1.topicid,
T1.code,
T1.description,
T1.parentid,
T1.parentid AS
NewParentID
,
Cast(T1.code AS NVARCHAR(max))
AS TopicCode,
Cast(T1.description AS NVARCHAR(max)) AS
TopicDescription,
Isnull(( accounting.documentdetail.debit ), 0) AS Debit,
Isnull(( accounting.documentdetail.credit ), 0) AS Credit
FROM accounting.topics AS T1
LEFT OUTER JOIN accounting.documentdetail
ON T1.topicid =
accounting.documentdetail.topicfk
WHERE NOT EXISTS(SELECT T2.topicid,
T2.code,
T2.description,
T2.parentid,
Isnull(( accounting.documentdetail.debit ), 0)
AS
Debit,
Isnull(( accounting.documentdetail.credit ), 0) AS
Credit
FROM accounting.topics AS T2
LEFT OUTER JOIN accounting.documentdetail
ON T2.topicid =
accounting.documentdetail.topicfk
WHERE ( parentid = T1.topicid )))
SELECT Isnull(Sum(debit), 0) AS Debit,
Isnull(Sum(credit), 0)AS Credit
FROM cte AS c
WHERE ( newparentid = #TopicID )
)
I think you Accounting.Topics hasn't column Debit.
UPDTAE
isnull((T1.Debit),0)+isnull(c.Debit,0) AS Debit,--IN THIS LINE error 'Invalid Column Name 'Debit''
isnull(c.Credit,0) AS Credit
FROM cte AS c
INNER JOIN Accounting.Topics AS T1
ON T1.TopicID = c.NewParentID
In the code above your T1.Debit refers to Accounting.Topics.

CROSS APPLY too slow for running total - TSQL

Please see my code below as it is running too slowly with the CROSS APPLY.
How can I remove the CROSS APPLY and add something else that will run faster?
Please note I am using SQL Server 2008 R2.
;WITH MyCTE AS
(
SELECT
R.NetWinCURRENCYValue AS NetWin
,dD.[Date] AS TheDay
FROM
dimPlayer AS P
JOIN
dbo.factRevenue AS R ON P.playerKey = R.playerKey
JOIN
dbo.vw_Date AS dD ON Dd.dateKey = R.dateKey
WHERE
P.CustomerID = 12345)
SELECT
A.TheDay AS [Date]
,ISNULL(A.NetWin, 0) AS NetWin
,rt.runningTotal AS CumulativeNetWin
FROM MyCTE AS A
CROSS APPLY (SELECT SUM(NetWin) AS runningTotal
FROM MyCTE WHERE TheDay <= A.TheDay) AS rt
ORDER BY A.TheDay
CREATE TABLE #temp (NetWin money, TheDay datetime)
insert into #temp
SELECT
R.NetWinCURRENCYValue AS NetWin
,dD.[Date] AS TheDay
FROM
dimPlayer AS P
JOIN
dbo.factRevenue AS R ON P.playerKey = R.playerKey
JOIN
dbo.vw_Date AS dD ON Dd.dateKey = R.dateKey
WHERE
P.CustomerID = 12345;
SELECT
A.TheDay AS [Date]
,ISNULL(A.NetWin, 0) AS NetWin
,SUM(B.NetWin) AS CumulativeNetWin
FROM #temp AS A
JOIN #temp AS B
ON A.TheDay >= B.TheDay
GROUP BY A.TheDay, ISNULL(A.NetWin, 0);
Here https://stackoverflow.com/a/13744550/613130 it's suggested to use recursive CTE.
;WITH MyCTE AS
(
SELECT
R.NetWinCURRENCYValue AS NetWin
,dD.[Date] AS TheDay
,ROW_NUMBER() OVER (ORDER BY dD.[Date]) AS RN
FROM dimPlayer AS P
JOIN dbo.factRevenue AS R ON P.playerKey = R.playerKey
JOIN dbo.vw_Date AS dD ON Dd.dateKey = R.dateKey
WHERE P.CustomerID = 12345
)
, MyCTERec AS
(
SELECT C.TheDay AS [Date]
,ISNULL(C.NetWin, 0) AS NetWin
,ISNULL(C.NetWin, 0) AS CumulativeNetWin
,C.RN
FROM MyCTE AS C
WHERE C.RN = 1
UNION ALL
SELECT C.TheDay AS [Date]
,ISNULL(C.NetWin, 0) AS NetWin
,P.CumulativeNetWin + ISNULL(C.NetWin, 0) AS CumulativeNetWin
,C.RN
FROM MyCTERec P
INNER JOIN MyCTE AS C ON C.RN = P.RN + 1
)
SELECT *
FROM MyCTERec
ORDER BY RN
OPTION (MAXRECURSION 0)
Note that this query will work if you have 1 record == 1 day! If you have multiple records in a day, the results will be different from the other query.
As I said here, if you want really fast calculation, put it into temporary table with sequential primary key and then calculate rolling total:
create table #Temp (
ID bigint identity(1, 1) primary key,
[Date] date,
NetWin decimal(29, 10)
)
insert into #Temp ([Date], NetWin)
select
dD.[Date],
sum(R.NetWinCURRENCYValue) as NetWin,
from dbo.dimPlayer as P
inner join dbo.factRevenue as R on P.playerKey = R.playerKey
inner join dbo.vw_Date as dD on Dd.dateKey = R.dateKey
where P.CustomerID = 12345
group by dD.[Date]
order by dD.[Date]
;with cte as (
select T.ID, T.[Date], T.NetWin, T.NetWin as CumulativeNetWin
from #Temp as T
where T.ID = 1
union all
select T.ID, T.[Date], T.NetWin, T.NetWin + C.CumulativeNetWin as CumulativeNetWin
from cte as C
inner join #Temp as T on T.ID = C.ID + 1
)
select C.[Date], C.NetWin, C.CumulativeNetWin
from cte as C
order by C.[Date]
I assume that you could have duplicates dates in the input, but don't want duplicates in the output, so I grouped data before puting it into the table.

Resources