Syntax error in Common Table Expression 1 - sql

I am trying to create a common table expression but I got an error.
Could you please help me with that.
WITH cte_sales AS(
SELECT
Payments.BankTransaction_Id,
Payments.Paid * InvoiceLines.TotalPrice / Invoices.TotalPayable AS PaymentAmount,
FORMAT( Cast(Payments.Paid / Invoices.TotalPayable as Decimal(6,1)) ,'P0') AS PaymentAmount,
Invoices.TotalPayable,
Payments.PaymentDate,
BankTransactions.TransactionDate,
ProductContracts.Product_Id,
ProductBases.Name AS ProductName,
ProductOptionBases.Name As ProductOptionName,
InvoiceLines.InvoiceLineId,
CubeOrder.Id AS ContractId,
ProductContracts.RowID AS ProductContractId
FROM Payments
INNER JOIN Invoices ON Invoices.Id = Payments.Invoice_Id
INNER JOIN InvoiceLines ON InvoiceLines.Invoice_Id = Invoices.Id
INNER JOIN ProductContracts ON CAST(ProductContracts.ContractID AS VARCHAR(100)) = SUBSTRING(InvoiceLines.InvoiceLineId, 1, 36)
INNER JOIN ProductOptionBases ON CAST(ProductOptionBases.Id AS VARCHAR(5)) = SUBSTRING(InvoiceLines.InvoiceLineId, 38, IIF (CHARINDEX(':', InvoiceLines.InvoiceLineId, 38) = 0, 999, CHARINDEX(':', InvoiceLines.InvoiceLineId, 38))- 38)
INNER JOIN ProductBases ON ProductContracts.Product_Id = ProductBases.Id
INNER JOIN CubeOrder ON CubeOrder.ContractID = Invoices.SubjectID
INNER JOIN BankTransactions ON BankTransactions.Id = Payments.BankTransaction_Id
WHERE ProductContracts.Discriminator = 'RecurringProductContract'
AND Invoices.TotalPayable <> 0
)
The error message is: Msg 102, Level 15, State 1, Line 26 Incorrect syntax near ')'.

You are missing the main query, that you need to add at the end.
For example, a query with a CTE should take the form:
with cte_sales as (
...
)
select * from cte_sales
You are missing that last line.

Related

I am converting Oracle queries to Standard Bigquery, i am gettting error "IN subquery is not supported inside join predicate."

I have converted oracle query into below standard bq but in last statement(IN subquery). I am getting error:
"IN subquery is not supported inside join predicate."
Please advise how to use IN subquery in bq in the below code
#Last part of the code
INNER JOIN (
SELECT
DISTINCT `domain-rr.oracle_DB_DB.he_project_assoc`.PARENT_ISBN
PARENT_ISBN,
SUM (`domain-rr.DB_RPT.PROJECT_GR_QTY`.GR_QTY) GR_QTY
FROM
`domain-rr.oracle_DB_DB.he_project_assoc`
INNER JOIN
`domain-rr.DB_RPT.PROJECT_GR_QTY`
ON
`domain-rr.oracle_DB_DB.he_project_assoc`.child_ISBN = `domain-
rr.DB_RPT.PROJECT_GR_QTY`.BIC_GCISBN
AND `domain-rr.oracle_DB_DB.he_project_assoc`.BREAK_LABEL <>
'Associated ISBNs'
GROUP BY
`domain-rr.oracle_DB_DB.he_project_assoc`.PARENT_ISBN) xx
ON
yy.PARENT_ISBN = xx.PARENT_ISBN
AND yy.CIRCULATION_INT < xx.GR_QTY
AND yy.PARENT_ISBN IN
( SELECT
DISTINCT _BIC_GCISBN
FROM
`domain-rr.DB_RPT.BIC_GM_AGCPOAODS00_BO_VW`
INNER JOIN
`domain-rr.oracle_DB_boadmin.fiscal_bo`
ON
_BIC_ZC2GRIRIN = 'G'
AND _BIC_ZCLOEKZ = ' '
AND SUBSTR (BOUND_DATE, 1, 6) = `domain-
rr.oracle_DB_boadmin.fiscal_bo`.PRIOR_FISC_YEAR_MONTH )
Can you try like this:
Select * from (
#Last part of the code
INNER JOIN (
SELECT
DISTINCT `pearson-rr.oracle_grdw_grdw.he_project_assoc`.PARENT_ISBN
PARENT_ISBN,
SUM (`pearson-rr.GRDW_RPT.PROJECT_GR_QTY`.GR_QTY) GR_QTY
FROM
`pearson-rr.oracle_grdw_grdw.he_project_assoc`
INNER JOIN
`pearson-rr.GRDW_RPT.PROJECT_GR_QTY`
ON
`pearson-rr.oracle_grdw_grdw.he_project_assoc`.child_ISBN = `pearson-
rr.GRDW_RPT.PROJECT_GR_QTY`.BIC_GCISBN
AND `pearson-rr.oracle_grdw_grdw.he_project_assoc`.BREAK_LABEL <>
'Associated ISBNs'
GROUP BY
`pearson-rr.oracle_grdw_grdw.he_project_assoc`.PARENT_ISBN) xx
ON
yy.PARENT_ISBN = xx.PARENT_ISBN
AND yy.CIRCULATION_INT < xx.GR_QTY
) AA
where AA.PARENT_ISBN IN
( SELECT
DISTINCT _BIC_GCISBN
FROM
`pearson-rr.GRDW_RPT.BIC_GM_AGCPOAODS00_BO_VW`
INNER JOIN
`pearson-rr.oracle_grdw_boadmin.fiscal_bo`
ON
_BIC_ZC2GRIRIN = 'G'
AND _BIC_ZCLOEKZ = ' '
AND SUBSTR (BOUND_DATE, 1, 6) = `pearson-
rr.oracle_grdw_boadmin.fiscal_bo`.PRIOR_FISC_YEAR_MONTH )

Progress SQL Column cannot be found or is not specified for query

I'm writing SQL against a Progress 10.2B07 database and am getting the following error "Column 'OUTERINVOICEHEADER.MEMBERID' cannot be found or is not specified for query (13865).
Here is the query:
select concat(substring(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6) + '-', OuterInvoiceHeader.sold_to_cust_seq) as MemberID,
sum(OuterInvoiceHeader.net_weight) as TotalInvoicePounds,
sum(OuterInvoiceHeader.net_weight / 2000) as TotalTons,
sum(OuterInvoiceHeader.invoice_amt) as InvoiceAmount,
sum(InvoiceSurcharges.Surcharge) as Surcharges,
sum(OuterInvoiceHeader.invoice_amt - InvoiceSurcharges.Surcharge) as Total,
sum(Returns.qty_received) as PoundsReturned
from AXS.PUB.ivc_header OuterInvoiceHeader
inner join
(select m.invoice_nbr, sum(m.extension) Surcharge from AXS.PUB.ivc_mchgs m
inner join
AXS.PUB.ivc_header h
on h.invoice_nbr = m.invoice_nbr
group by m.invoice_nbr) InvoiceSurcharges
on OuterInvoiceHeader.invoice_nbr = InvoiceSurcharges.invoice_nbr
left outer join
(select concat(substring(ReturnHeader.ship_to_nbr, 1, 6)+'-',InnerInvoiceHeader.sold_to_cust_seq) as ReturnMemberID,
ReturnHeader.invoice_nbr as ReturnInvoiceNum,
qty_received
from AXS.PUB.return_hdr ReturnHeader
inner join
AXS.PUB.ivc_header InnerInvoiceHeader
on ReturnHeader.invoice_nbr = InnerInvoiceHeader.invoice_nbr
inner join AXS.PUB.return_line ReturnLine
on ReturnHeader.claim_nbr = ReturnLine.claim_nbr
where ReturnInvoiceNum = '0001010914'
group by ReturnMemberID, ReturnInvoiceNum, qty_received) Returns
on OuterInvoiceHeader.MemberID = Returns.ReturnMemberID
--on OuterInvoiceHeader.invoice_nbr = Returns.ReturnInvoiceNum
where OuterInvoiceHeader.sold_to_cust_nbr = '000837' and OuterInvoiceHeader.invoice_date between '06/01/2016' and '06/30/2016' and OuterInvoiceHeader.invoice_status = '5804' and OuterInvoiceHeader.invoice_type='5601'
group by MemberID
The problem is in the left join; the commented out on clause "on OuterInvoiceHeader.invoice_nbr = Returns.ReturnInvoiceNum" will work if uncommented. The "on OuterInvoiceHeader.MemberID = Returns.ReturnMemberID" clause gives me the error.
What I don't understand is that both of these reference a column in the top SELECT statement, the only difference is that one is a concatenation and the other is not.
I hope that I just can't see the forest for the trees here and the answer is simple, so if anyone has any suggestions or questions I'm all ears.
try this:
I replaced the references to the alias MemberID to be the actual concatinated columns CONCAT(SUBSTRING(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6)+'-', OuterInvoiceHeader.sold_to_cust_seq)
SELECT CONCAT(SUBSTRING(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6)+'-', OuterInvoiceHeader.sold_to_cust_seq) AS MemberID
, SUM(OuterInvoiceHeader.net_weight) AS TotalInvoicePounds
, SUM(OuterInvoiceHeader.net_weight / 2000) AS TotalTons
, SUM(OuterInvoiceHeader.invoice_amt) AS InvoiceAmount
, SUM(InvoiceSurcharges.Surcharge) AS Surcharges
, SUM(OuterInvoiceHeader.invoice_amt - InvoiceSurcharges.Surcharge) AS Total
, SUM(Returns.qty_received) AS PoundsReturned
FROM AXS.PUB.ivc_header OuterInvoiceHeader
INNER JOIN
(SELECT m.invoice_nbr
, SUM(m.extension) Surcharge
FROM AXS.PUB.ivc_mchgs m
INNER JOIN AXS.PUB.ivc_header h ON h.invoice_nbr = m.invoice_nbr
GROUP BY m.invoice_nbr) InvoiceSurcharges ON OuterInvoiceHeader.invoice_nbr = InvoiceSurcharges.invoice_nbr
LEFT OUTER JOIN
(SELECT CONCAT(SUBSTRING(ReturnHeader.ship_to_nbr, 1, 6)+'-', InnerInvoiceHeader.sold_to_cust_seq) AS ReturnMemberID
, ReturnHeader.invoice_nbr AS ReturnInvoiceNum
, qty_received
FROM AXS.PUB.return_hdr ReturnHeader
INNER JOIN AXS.PUB.ivc_header InnerInvoiceHeader ON ReturnHeader.invoice_nbr = InnerInvoiceHeader.invoice_nbr
INNER JOIN AXS.PUB.return_line ReturnLine ON ReturnHeader.claim_nbr = ReturnLine.claim_nbr
WHERE ReturnInvoiceNum = '0001010914'
GROUP BY ReturnMemberID
, ReturnInvoiceNum
, qty_received) Returns ON CONCAT(SUBSTRING(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6)+'-', OuterInvoiceHeader.sold_to_cust_seq) = Returns.ReturnMemberID
--on OuterInvoiceHeader.invoice_nbr = Returns.ReturnInvoiceNum
WHERE OuterInvoiceHeader.sold_to_cust_nbr = '000837'
AND OuterInvoiceHeader.invoice_date BETWEEN '06/01/2016' AND '06/30/2016'
AND OuterInvoiceHeader.invoice_status = '5804'
AND OuterInvoiceHeader.invoice_type = '5601'
GROUP BY CONCAT(SUBSTRING(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6)+'-', OuterInvoiceHeader.sold_to_cust_seq);
Basically you need to keep in mind the order which SQL statements are executed:
FROM clause
WHERE clause
GROUP BY clause
HAVING clause
SELECT clause
ORDER BY clause
That's a computed column alias and thus the error. You should consider using the entire expression rather like
on concat(substring(OuterInvoiceHeader.sold_to_cust_nbr, 1, 6) + '-', OuterInvoiceHeader.sold_to_cust_seq) = Returns.ReturnMemberID
Instead of on OuterInvoiceHeader.MemberID = Returns.ReturnMemberID. As well, change any other place where you are using the same alias. You can and should use that alias only in a outer query and not in the same query.

Rows to Columns with Row as Column Name Grouping

I have a query which I need to transpose the rows returned into separate columns, but I need the column names returned from the row values, and another field as the value under these columns.
Ultimately this will be going into Excel. I initially thought I could do it with a pivot, but the values field cannot accept text without some work, and there are too many "film right types" to work with. I know the specific rights type currently, but the right descriptions and number of rights may change in the future, so I want it to be as flexible as possible.
I want to group by producer, film and country, with the "Film Right Type" as the columns going across, and the "Availability" as the value for the right type column.
My query as it stands.
Select product_detail.pd_product_code as 'ProductCode',
product_analysis.pa_m_9 as 'Producer',
product_detail.pd_abbv_description as 'Film',
product_detail.pd_commodity_code as 'Country',
variant_analysis.vaa_c_10 as 'Film Right Type',
case when isnull(variant_analysis.vaa_l_1,0) = 0 then 'Non-Exclusive'
Else
case when dateadd(day,datediff(DAY,0,isnull(orders.LastDate,getdate())),0) > dateadd(day,datediff(DAY,0,getdate()),0)
Then 'Available On '+convert(varchar(10),Orders.LastDate, 103)
Else 'Available'
End
end as 'Availability'
From product_detail
join variant_detail on variant_detail.vad_pd_id = product_detail.pd_id
left join variant_analysis on variant_analysis.vaa_vad_id = variant_Detail.vad_id
left join product_analysis on product_analysis.pa_pd_id = product_detail.pd_id
join (select count(variant_detail.vad_id) as CountVariants, variant_Detail.vad_pd_id from variant_Detail group by variant_detail.vad_pd_id) as Variants on Variants.vad_pd_id = product_detail.pd_id
Outer Apply
(select top 1
customer_detail.cd_statement_name as Customer,
order_header_analysis.oha_d_2 as LastDate,
system_order_type.sot_description as OrderType,
order_header.oh_order_number as OrderNo
from order_header
join customer_detail on customer_detail.cd_id = order_header.oh_cd_id
join order_line_item on order_line_item.oli_oh_id = order_header.oh_id
join system_order_type on system_order_type.sot_id = order_header.oh_sot_id
left join order_header_analysis on order_header_analysis.oha_oh_id = order_header.oh_id
where order_header_analysis.oha_d_2 >= getdate()
and order_header.oh_sot_id in (1, 2, 3)
and order_line_item.oli_vad_id = variant_detail.vad_id
ORder By order_header_analysis.oha_d_2 desc) as Orders
where isnull(variant_analysis.vaa_l_2,0) = 0
This is the data I currently get out of it:
This is how I want the end result.
Edit:
I have nearly got this doing what I want after using a pivot.
My below query gives me exactly what I need:
Select *
From(
Select product_detail.pd_product_code as 'ProductCode',
product_analysis.pa_m_9 as 'Producer',
product_detail.pd_abbv_description as 'Film',
product_detail.pd_commodity_code as 'Country',
variant_analysis.vaa_c_10 as 'FilmRightType',
case when isnull(variant_analysis.vaa_l_1,0) = 0 then 'Non-Exclusive'
Else
case when dateadd(day,datediff(DAY,0,isnull(orders.LastDate,getdate())),0) > dateadd(day,datediff(DAY,0,getdate()),0)
Then 'Available On '+convert(varchar(10),Orders.LastDate, 103)
Else 'Available'
End
end as 'Availability'
From product_detail
join variant_detail on variant_detail.vad_pd_id = product_detail.pd_id
left join variant_analysis on variant_analysis.vaa_vad_id = variant_Detail.vad_id
left join product_analysis on product_analysis.pa_pd_id = product_detail.pd_id
join (select count(variant_detail.vad_id) as CountVariants, variant_Detail.vad_pd_id from variant_Detail group by variant_detail.vad_pd_id) as Variants on Variants.vad_pd_id = product_detail.pd_id
Outer Apply
(select top 1
customer_detail.cd_statement_name as Customer,
order_header_analysis.oha_d_2 as LastDate,
system_order_type.sot_description as OrderType,
order_header.oh_order_number as OrderNo
from order_header
join customer_detail on customer_detail.cd_id = order_header.oh_cd_id
join order_line_item on order_line_item.oli_oh_id = order_header.oh_id
join system_order_type on system_order_type.sot_id = order_header.oh_sot_id
left join order_header_analysis on order_header_analysis.oha_oh_id = order_header.oh_id
where order_header_analysis.oha_d_2 >= getdate()
and order_header.oh_sot_id in (1, 2, 3)
and order_line_item.oli_vad_id = variant_detail.vad_id
ORder By order_header_analysis.oha_d_2 desc) as Orders
where isnull(variant_analysis.vaa_l_2,0) = 0
) as FilmVals
pivot
(
max(Availability)
for FilmRightType in (
[Theatrical], [DVD], [Blu ray], [Free TV], [Pay TV], [Video on Demand Catch Up], [Subscription Video on Demand], [Advertising Video on Demand], [TV On Demand Download to Own], [TV On Demand Download to Rent]
)
) piv;
I want to set the list of RightTypes to be dynamic from the DB.
I've created another query using for XML Path and this returns the data in the correct format:
(Select left(RightType.RightTypesList,len(RightType.RightTypesList)-1) From (Select
(Select
DISTINCT
'['+variant_analysis.vaa_c_10+']'+', '
from variant_analysis
where variant_analysis.vaa_c_10 is not null
order by 1
For XML Path ('')) as RightTypesList) as RightType)
But when I put this in place of the hard coded list, I get the following error:
Msg 102, Level 15, State 1, Line 44
Incorrect syntax near '('.
Msg 102, Level 15, State 1, Line 52
Incorrect syntax near ')'.
Try to use PIVOT operator in SQL
Here is an example

Left Join with Case Statement in Sql Server getting ERROR

SELECT
Camp.ID, Inst.StartDate, Ctype.CampaignType,
'Cert' + REPLACE(Ctype.CampaignType, ' ', '') AS CampaignType
FROM
CertCampaign Camp
LEFT JOIN
(SELECT
CASE WHEN CampaignType = 'CertAccounttoRole' THEN CertUserToAccount) t ON Inst.ID = t.InstanceId
LEFT JOIN
CertAccounttoRole ON Inst.ID = t.InstanceId
LEFT JOIN
CertCampaignType Ctype ON Ctype.ID = Camp.CampaignTypeId
LEFT JOIN
CertInstance Inst ON Inst.CampaignId = Camp.ID
Getting error:
Msg 102, Level 15, State 1, Line 6
Incorrect syntax near ')'.
You need an END in your case stmt, you will also have to name that column:
LEFT JOIN(select case when CampaignType='CertAccounttoRole'
then CertUserToAccount
end as InstanceId )t ON
Inst.ID=t.InstanceId

SQL query: Incorrect syntax near the keyword 'TOP'

SELECT #Tax = SUM(QuoteItem.SalesPrice) * TOP (1) Tax.Amount
FROM Tax INNER JOIN
Job ON Tax.TaxId = Job.TaxId INNER JOIN
Quote ON Job.JobId = Quote.JobId INNER JOIN
QuoteItem INNER JOIN
Room ON QuoteItem.RoomId = Room.RoomId ON Quote.QuoteId = Room.QuoteId
WHERE (Room.QuoteId = #QuoteId) AND (QuoteItem.UnitId = #UnitId)
RETURN #Tax
Result:
Msg 156, Level 15, State 1, Procedure fn_GetQuoteUnitTax, Line 54
Incorrect syntax near the keyword 'TOP'.
Note, that when I omit the TOP(1) it says:
Msg 8120, Level 16, State 1, Procedure fn_GetQuoteUnitTax, Line 54
Column 'Tax.Amount' is invalid in the select list because it is not contained in
either an aggregate function or the GROUP BY clause.
I think you need to do this in two separate queries. The first gets the tax amount:
select #tax = Tax.Amount
from Tax
inner join ...whatever else you need here...
where ...
Note that you can't use the 'top' clause when setting the #tax variable value - you will need to do something in your where clause to select the value you want.
Then get the sales price:
select #sales = sum(QuoteItem.SalesPrice
from ...
where ...
Finally return the result:
return #tax * #sales
According to http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=137110:
SELECT #Tax = SUM(QuoteItem.SalesPrice * Tax.Amount)