WITH Clause Syntax error - While using Outer select - sql

I have created a sql which is below, when i am trying to put this under outer select which will l just display the results that are rendered from below WITH clause query it is giving me error in sql server, where as working fine with Oracle.
I don't want to create a view i want to put this below ouptut in merge statement...
select custno, slipno, category, donation, unique_nm from
(
-- Here it is throwing error
with got_debit_custno (custno, slipno, category, donation, debit_custno) as
(
select custno, slipno, category, donation
, case
when category = 'CREDIT'
then 'N/A'
else custno
end
from a
)
, prep (custno, slipno, category, donation, debit_custno, rn, rdt) as
(
select dc.*
, row_number () over (partition by debit_custno, category order by donation, slipno)
, sum (donation) over (partition by debit_custno, category order by donation, slipno)
from got_debit_custno dc
)
, r (custno, slipno, category, donation, debit_custno, rn, rdt, mn) as
(
select custno, slipno, category, donation, debit_custno
, case
when rn = max(rn) over (partition by debit_custno, category)
then rn
end
, rdt, 1
from prep
where rdt <= 27000 or rn = 1
union all
select p.custno, p.slipno, p.category, p.donation, p.debit_custno
, case
when p.rn = max(p.rn) over (partition by p.debit_custno, p.category)
then p.rn
end
, p.rdt, r.mn + 1
from prep p
join r on p.debit_custno = r.debit_custno
and p.category = r.categoRy
and p.rn > r.rn
and (p.rdt <= r.rdt + 27000 or p.rn = r.rn + 1)
)
select custno, slipno, category, donation
, dense_rank () over (order by debit_custno, category, mn) as unique_nm
from r)
order by custno, unique_nm, donation

WITH must be the first keyword of the query. The previous statement must be be terminated by ; as:
;WITH got_debit_custno (custno, slipno, category, donation, debit_custno) as
(
select custno, slipno, category, donation
, case
when category = 'CREDIT'
then 'N/A'
else custno
end
from a
)
, prep (custno, slipno, category, donation, debit_custno, rn, rdt) as
(
select dc.*
, row_number () over (partition by debit_custno, category order by donation, slipno)
, sum (donation) over (partition by debit_custno, category order by donation, slipno)
from got_debit_custno dc
)
, r (custno, slipno, category, donation, debit_custno, rn, rdt, mn) as
(
select custno, slipno, category, donation, debit_custno
, case
when rn = max(rn) over (partition by debit_custno, category)
then rn
end
, rdt, 1
from prep
where rdt <= 27000 or rn = 1
union all
select p.custno, p.slipno, p.category, p.donation, p.debit_custno
, case
when p.rn = max(p.rn) over (partition by p.debit_custno, p.category)
then p.rn
end
, p.rdt, r.mn + 1
from prep p
join r on p.debit_custno = r.debit_custno
and p.category = r.categoRy
and p.rn > r.rn
and (p.rdt <= r.rdt + 27000 or p.rn = r.rn + 1)
)
select custno, slipno, category, donation
, dense_rank () over (order by debit_custno, category, mn) as unique_nm
from r
order by custno, unique_nm, donation

Related

Problem with Recursive CTE very long query plan

When I execute below query SQL run this plan and it took a long time to run it and it will not be over.
QueryPlanLink
I have 3 million records in #T table.
myCode:
;WITH cte1 AS (
SELECT NationalId,len(NationalId) as LenNationalId,CustomerType,FullDateInt,time,
SUM(Price) as SUMPrice
,AVG(Price) as Price
,SUM(Volume) as Volume
,SUM (sum([Volume])) OVER (PARTITION BY NationalId,len(NationalId) ORDER BY FullDateInt,[Time]) as SumVol
,ROW_NUMBER() OVER (PARTITION BY NationalId,len(NationalId) ORDER BY FullDateInt,[Time]) AS rn
from #T as T1
group by NationalId,len(NationalId),CustomerType,FullDateInt,time
), rcte AS (
SELECT *, Price AS Cost , cast(0 as decimal) as Profit
FROM cte1 AS base
WHERE base.rn = 1
UNION ALL
SELECT curr.*, Case when curr.Volume>0 Then ((curr.Volume *curr.Price) + (prev.Cost*prev.SumVol))/nullif(curr.SumVol,0)
when curr.Volume<0 Then prev.Cost
End
as Cost
,ISNULL(Cast (Case when curr.Volume<0 Then -1*(curr.Price-Cost)*curr.Volume End as decimal),0) as Profit
FROM cte1 AS curr
INNER JOIN rcte AS prev
ON curr.NationalId = prev.NationalId AND curr.rn = prev.rn + 1
)
Select * from rcte
option (maxrecursion 0)
Is there any way to make it better?
Thanks
I Change My Query like below And Everything is Done. Thanks For All.
SELECT NationalId,len(NationalId) as LenNationalId,CustomerType,FullDateInt,time,
SUM(Price) as SUMPrice
,AVG(Price) as Price
,SUM(Volume) as Volume
,SUM (sum([Volume])) OVER (PARTITION BY NationalId,len(NationalId) ORDER BY FullDateInt,[Time]) as SumVol
,ROW_NUMBER() OVER (PARTITION BY NationalId,len(NationalId) ORDER BY FullDateInt,[Time]) AS rn
into #TCTE from #T as T1
group by NationalId,len(NationalId),CustomerType,FullDateInt,time
;With rcte AS (
SELECT *, Price AS Cost , cast(0 as decimal) as Profit
FROM #TCTE AS base
WHERE base.rn = 1
UNION ALL
SELECT curr.*, Case when curr.Volume>0 Then ((curr.Volume *curr.Price) + (prev.Cost*prev.SumVol))/nullif(curr.SumVol,0)
when curr.Volume<0 Then prev.Cost
End
as Cost
,ISNULL(Cast (Case when curr.Volume<0 Then -1*(curr.Price-Cost)*curr.Volume End as decimal),0) as Profit
FROM #TCTE AS curr
INNER JOIN rcte AS prev
ON curr.NationalId = prev.NationalId AND curr.rn = prev.rn + 1
)
Select *
into #TFinal from rcte
option (maxrecursion 0)

Bring next value after condition

I am trying to fetch the next value after the condition is found. In this case, it is a row from 13/05/2021 the result I want to see is the row from 19/05/2021 Cte and CTE1 bring correct results.
I can't figure out what is wrong with my query.
<with cte as
(
select
customerid
,max(timestamp) as [Case Submitted]
,row_number() over (partition by [CustomerId] order by [CustomerId] ,max([timestamp]) desc) as rownum
from Table1
where substatus = 'Case Submitted'
and timestamp > '2021-01-01'
Group by
customerid
,timestamp
)
,CTE2 as
(
Select *
from cte
Where rownum = 1
),
CTE3 as
(
select
PS.customerid
,(PS.timestamp) as [Customer Support]
,row_number() over (partition by PS.customerid order by PS.customerid ) as rownum
from Table1 PS
left join CTE2 C2 on C2.customerid = PS.customerid and C2.[Case Submitted] > PS.timestamp and C2.rownum =1
where status = 'Customer Support'
and timestamp > '2021-01-01'
Group by
PS.customerid
,ps.timestamp
)
Select*
from CTE3>
untested notepad scribble
with CTE1 as
(
select
customerid
, [timestamp] as [Case Submitted]
, rownum = row_number() over (partition by CustomerId order by [timestamp] desc)
from Table1
where substatus = 'Case Submitted'
and [timestamp] > cast('2021-01-01' as date)
),
CTE2 AS
(
select
PS.customerid
, PS.timestamp as [Customer Support]
, rownum = row_number() over (partition by PS.customerid order by PS.timestamp)
from Table1 as PS
join CTE1 as C1
on C1.customerid = PS.customerid
and C1.[Case Submitted] > PS.[timestamp]
and C1.rownum = 1
where PS.status = 'Customer Support'
and [timestamp] > cast('2021-01-01' as date)
)
select *
from CTE2
where rownum = 1

Mandt Specified Multiple Times But Not in Query

I get this error
Msg 8156, Level 16, State 1, Line 67
The column 'MANDT' was specified multiple times for 'cte'."
when attempting to run the code below however I am not including the column MANDT in my query. Both tables that I am calling do have a column MANDT, but they both have the column STAT as well and I did not have a problem with another table attempting the same join, the only thing is that table did not have MANDT, only STAT was the same.
I attempted to include both columns MANDT with an alias: JCDS_SOGR.MANDT as Client and TJ30T.MANDT as Client2 separately and together, this did not pan out. Got the same error message.
;WITH cte AS
(
SELECT
ROW_NUMBER() OVER (PARTITION BY STAT ORDER BY UDATE) AS Rn,
*,
LAG(UDATE) OVER (PARTITION BY STAT ORDER BY UDATE) AS PrevUDate,
COUNT(*) OVER (PARTITION BY STAT) AS [Count]
FROM
JCDS_SOGR
JOIN
TJ30T on JCDS_SOGR.STAT = TJ30T.ESTAT
WHERE
OBJNR = 'IE000000000010003137'
)
SELECT
MAX(rn) AS [Count],
OBJNR, STAT, TXT30,
SUM(CASE
WHEN rn % 2 = 0
THEN DATEDIFF(d, PrevUDate, UDATE)
WHEN rn = [Count]
THEN DATEDIFF(d, UDATE, GETDATE())
ELSE 0
END) AS DIF
FROM
cte
GROUP BY
OBJNR, STAT, TXT30
This is the other query I referred to that works fine with this same code.
;with cte
AS
(
select ROW_NUMBER() OVER(partition by STAT Order by UDATE ) as Rn
, *
, LAG(UDATE) OVER(partition by STAT Order by UDATE ) As PrevUDate
, COUNT(*) OVER(partition by STAT) As [Count]
from JCDS_SOGR
join TJ02T on JCDS_SOGR.STAT = TJ02T.ISTAT
where OBJNR = 'IE000000000010003137'
and TJ02T.SPRAS = 'E'
)
select Max(rn) As [Count]
, OBJNR,STAT,TXT30
, SUM(CASE WHEN rn%2=0 THEN DATEDIFF(d,PrevUDate,UDATE)
WHEN rn=[Count] THEN DATEDIFF(d,UDATE,getDate())
ELSE 0 END) as DIF
from cte
group BY OBJNR, STAT,TXT30
The expected result is this
[COUNT OBJNR STAT TXT30 DIF
1 IE000000000010003137 I0099 Available 2810][1]
In your CTE, you are selecting *. So if you have two columns named MANDT, this could cause a conflict. Remove *. That should fix the problem that you described.

TSQL Row_Number

This question has been covered similarly before BUT I'm struggling.
I need to find top N sales based on customer buying patterns..
ideally this needs to be top N by customer by Month Period by Year but for now i'm just looking at top N over the whole DB.
My query looks like:
-- QUERY TO SHOW TOP 2 CUSTOMER INVOICES BY CUSTOMER BY MONTH
SELECT
bill_to_code,
INVOICE_NUMBER,
SUM( INVOICE_AMOUNT_CORP ) AS 'SALES',
ROW_NUMBER() OVER ( PARTITION BY bill_to_code ORDER BY SUM( INVOICE_AMOUNT_CORP ) DESC ) AS 'Row'
FROM
FACT_OM_INVOICE
JOIN dim_customer_bill_to ON FACT_OM_INVOICE.dim_customer_bill_to_key = dim_customer_bill_to.dim_customer_bill_to_key
--WHERE
-- 'ROW' < 2
GROUP BY
invoice_number,
Dim_customer_bill_to.bill_to_code
I can't understand the solutions given to restrict Row to =< N.
Please help.
Try this.
-- QUERY TO SHOW TOP 2 CUSTOMER INVOICES BY CUSTOMER BY MONTH
;WITH Top2Customers
AS
(
SELECT
bill_to_code,
INVOICE_NUMBER,
SUM( INVOICE_AMOUNT_CORP ) AS 'SALES',
ROW_NUMBER() OVER ( PARTITION BY bill_to_code ORDER BY SUM( INVOICE_AMOUNT_CORP ) DESC )
AS 'RowNumber'
FROM
FACT_OM_INVOICE
JOIN dim_customer_bill_to ON FACT_OM_INVOICE.dim_customer_bill_to_key = dim_customer_bill_to.dim_customer_bill_to_key
GROUP BY
invoice_number,
Dim_customer_bill_to.bill_to_code
)
SELECT * FROM Top2Customers WHERE RowNumber < 3
You have to wrap your select into another to use the value produced by row_number()
select * from (
SELECT
bill_to_code,
INVOICE_NUMBER,
SUM( INVOICE_AMOUNT_CORP ) AS SALES,
ROW_NUMBER() OVER ( PARTITION BY bill_to_code ORDER BY SUM( INVOICE_AMOUNT_CORP ) DESC ) AS RowNo
FROM
FACT_OM_INVOICE
JOIN dim_customer_bill_to ON FACT_OM_INVOICE.dim_customer_bill_to_key = dim_customer_bill_to.dim_customer_bill_to_key
--WHERE
-- 'ROW' < 2
GROUP BY
invoice_number,
Dim_customer_bill_to.bill_to_code
) base where RowNo < 2

sql partiton by suppress repeating values

Using SQL Server (2005/2008)
Is there an easy way to suppress the repeating sub & grand totals?
select h.salesmanno
,c.custname
,h.amt
,sum(h.amt) over (partition by salesmanno) as subtotal
,sum(h.amt) over (partition by null) as grandtotal
from hdr h, cust c WHERE h.custno = c.custno
and h.hdate = '6/8/2009'
basically suppress (or null) except the last position, before the group change
Thanks!!
What database is this? On SQL Server, something like this would do:
select
salesmanno, custname, amt
, case when subtotal_no = subtotal_count then subtotal end as subtotal
, case when total_no = total_count then subtotal end as total
from (
select
h.salesmanno
, c.custname
, h.amt
, sum(h.amt) over (partition by salesmanno) as subtotal
, sum(h.amt) over (partition by null) as grandtotal
, row_number() over (partition by salesmanno order by custname) as subtotal_no
, row_number() over (partition by null order by salesmanno, custname) as as total_no
, count(*) over (parition by salesmanno) as subtotal_count
, count(*) over (parition by null) as total_count
from hdr h, cust c
WHERE h.custno = c.custno
and h.hdate = '6/8/2009'
) a
order by total_no
Shorter version, more sorting for the database, maybe less obvious what's going on:
select
salesmanno, custname, amt
, case when subtotal_no = 1 then subtotal end as subtotal
, case when total_no = 1 then subtotal end as total
from (
select
h.salesmanno
, c.custname
, h.amt
, sum(h.amt) over (partition by salesmanno) as subtotal
, sum(h.amt) over (partition by null) as grandtotal
, row_number() over (partition by salesmanno order by custname desc) as subtotal_no
, row_number() over (partition by null order by salesmanno desc, custname desc) as as total_no
from hdr h, cust c
WHERE h.custno = c.custno
and h.hdate = '6/8/2009'
) a
order by total_no desc
Alternatively, using ROLLUP to generate subtotal and total rows:
select
h.salesmanno
, c.custname
, sum(h.amt) as amt
from hdr h, cust c
WHERE h.custno = c.custno
and h.hdate = '6/8/2009'
group by
h.salesmanno
, c.custname
with rollup
order by
h.salesmanno
, c.custname
To get the results in the proper order, change the order by to something like this:
order by
grouping(h.salesmanno)
, h.salesmanno
, grouping(c.custname)
, c.custname
Nest this in a subquery and add your filter in a WHERE:
SELECT *
FROM (
select h.salesmanno ,c.custname ,h.amt ,sum(h.amt) over (partition by salesmanno) as subtotal
,sum(h.amt) over (partition by null) as grandtotal
from hdr h, cust c WHERE h.custno = c.custno and h.hdate = '6/8/2009'
) AS X
WHERE whatever