Syntax error in query expression using sub query - sql

SELECT
(
SELECT Sum(tbl_allTransactions.transAmount) AS SumOftransAmount
FROM tbl_allTransactions
WHERE (((tbl_allTransactions.[transType])='Expense')) OR (((tbl_allTransactions.[transType])='Budget') AND ((tbl_allTransactions.[transMonth])=[#transMonth]))
GROUP BY tbl_allTransactions.transMonth
,
SELECT Sum(tbl_allTransactions.transAmount) AS SumOftransAmount
FROM tbl_allTransactions
WHERE (((tbl_allTransactions.[transType])='Expense')) OR (((tbl_allTransactions.[transType])='Budget') AND ((tbl_allTransactions.[transMonth])=[#transMonth]))
GROUP BY tbl_allTransactions.transMonth
)
FROM tbl_allTransactions WHERE (((tbl_allTransactions.[userID])=[#userID]))
I am getting following error:-
System.Data.OleDb.OleDbException (0x80040E14) Syntax error in query
expression '(SELECT Sum(tbl_allTransactions.transAmount) AS
SumOftransAmount FROM tbl_allTransactions WHERE
(((tbl_allTransactions.[transType])='Expense')) OR
(((tbl_allTransactions.[transType])='Budget') AND
((tbl_allTransactions.[transMonth])=[#transMonth])) GROUP '. at
System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResulthr) at
System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS
dbParams, Object& executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteCommandText(Obje

The original code was missing a closing parenthesis on the first subquery. The code was also simplified by consolidating the transType conditional from 2 statements to 1. Extra brackets were removed to enhance readability. Also column aliases were added to output of each subquery. Since both queries render the same data, the second column was called "SumOftransAmount2"
SELECT
(SELECT Sum(tbl_allTransactions.transAmount)
FROM tbl_allTransactions
WHERE tbl_allTransactions.transType in ('Expense', 'Budget') AND tbl_allTransactions.transMonth = #transMonth
GROUP BY tbl_allTransactions.transMonth) as SumOftransAmount
,
(SELECT Sum(tbl_allTransactions.transAmount)
FROM tbl_allTransactions
WHERE tbl_allTransactions.transType in ('Expense', 'Budget') AND tbl_allTransactions.transMonth = #transMonth
GROUP BY tbl_allTransactions.transMonth) as SumOftransAmount2
FROM tbl_allTransactions
WHERE tbl_allTransactions.userID=#userID

Related

Pivot query causing "incorrect syntax" error in the PIVOT clause

I am getting the error, "incorrect syntax near 'Basic'" when I try to execute the following query:
WITH BaseQuery AS (
SELECT Region,Essbase_Channel,Product,COUNT(New_reconnects)
FROM NDW.dbo.SOS_Detail SOS
WHERE SOS.EntityID IN ('000310','000700','000815','000854')
AND Division ='NORTHEAST DIVISION' AND Month_Name ='MAR'
GROUP BY Month_Name,Product,Region,Essbase_Channel,EntityID,Division
)
SELECT * FROM BaseQuery
PIVOT (COUNT(New_reconnects) FOR Product IN ('BASIC','HSI','CDV','H1','X1')) AS PVT
ORDER BY Product,Region,Essbase_Channel
My goal would be to have the first column based on Essbase_Channel, the pivot columns to be Product values: BASIC, HSI, CDV, H1 and the values in the pivot to be COUNT(New_reconnects).
How should I change the syntax of the query to avoid this error?
Change to:
FOR Product IN ([BASIC],[HSI],[CDV],[H1],[X1])

How can I make sure results from a CASE Statement are not shown in my query? [duplicate]

I am running into the error stated in the Title when I attempt to use the alias of a decode in my select statement. Here is the code:
SELECT DISTINCT rl.complaint_date,
decode(rl.judgement_date,null,rl.complaint_amt,rl.judgement_amt) as account_amt,
rl.date_served1,
rl.date_served2,
rl.judgement_date,
rl.skip_locate,
rl.case_no,
lcc.bal_range_min,
lcc.bal_range_max,
lcc.cost_range_min,
lcc.cost_range_max,
lcc.court,
lcc.county AS lcc_county,
ah.ACCOUNT,
ah.transaction_code,
ah.transaction_date,
ah.rule_id,
ah.amount,
ah.description,
r.state,
r.zip_code,
z.county AS ah_county,
z.county_2,
z.county_3,
z.county_4
FROM legal_address_skip las,
racctrel r,
ziplist z,
legal_court_cost lcc,
racctlgl rl,
legal_transaction_review ah
WHERE ah.ACCOUNT = rl.ACCOUNT
AND ah.ACCOUNT = las.ACCOUNT(+)
AND ah.ACCOUNT = r.ACCOUNT
AND nvl(lpad(substr(r.zip_code,0,instr(r.zip_code,'-')-1),5,0), substr(r.zip_code,1,5)) = z.zip
AND r.state = lcc.state
AND (REPLACE(lcc.county,' ','') = REPLACE(upper(z.county),' ','')
OR REPLACE(lcc.county,' ','') = REPLACE(upper(z.county_2),' ','')
OR REPLACE(lcc.county,' ','') = REPLACE(upper(z.county_3),' ','')
OR REPLACE(lcc.county,' ','') = REPLACE(upper(z.county_4),' ',''))
AND lcc.transaction_code = ah.transaction_code
AND lcc.transaction_code = 1
AND lcc.end_date IS NULL
AND ah.amount NOT BETWEEN lcc.cost_range_min AND lcc.cost_range_max
AND (account_amt NOT BETWEEN lcc.bal_range_min AND lcc.bal_range_max
OR lcc.bal_range_min - account_amt NOT BETWEEN 0 AND 500)
ORDER BY CASE
WHEN ah.amount NOT BETWEEN lcc.cost_range_min AND lcc.cost_range_max THEN 1
WHEN ah.amount BETWEEN lcc.cost_range_min AND lcc.cost_range_max THEN 2 END, ah.amount;
I've used aliases before in select statements so I'm confused on why I am getting an error for this. Does it work differently in this situation?
From the documentation (emphasis added):
You can use a column alias, c_alias, to label the immediately
preceding expression in the select list so that the column is
displayed with a new heading. The alias effectively renames the select
list item for the duration of the query. The alias can be used in the
ORDER BY clause, but not other clauses in the query.
So you can't refer to the alias in the where clause, where at the moment you have:
...
AND (account_amt NOT BETWEEN ...
...
The alias isn't valid at that point, so it's looking for a column with that name in one of the tables, and doesn't find one. It's fine in the order by though.
You either need to replace the alias with the repeated decode statement, or possibly use a subquery and then refer to the alias in a where clause in an outer query, but that might end up being less efficient depending on how selective your other conditions are.
Oracle runs the select query in the order below:
FROM clause
WHERE clause
GROUP BY clause
HAVING clause
SELECT clause
ORDER BY clause
Based on the above, you can see that when you are in the WHERE part, the alias has not yet been created. If you would like to use results from the SELECT part, you can do that by modifying your query like this:
WITH q AS
(
-- Your query without the extra AND
)
SELECT *
FROM q
WHERE --put your check here
This way you will already have the alias available when you reach the WHERE part.
Hope this helps! :)

ORA-00904 invalid identifier on decode alias

I am running into the error stated in the Title when I attempt to use the alias of a decode in my select statement. Here is the code:
SELECT DISTINCT rl.complaint_date,
decode(rl.judgement_date,null,rl.complaint_amt,rl.judgement_amt) as account_amt,
rl.date_served1,
rl.date_served2,
rl.judgement_date,
rl.skip_locate,
rl.case_no,
lcc.bal_range_min,
lcc.bal_range_max,
lcc.cost_range_min,
lcc.cost_range_max,
lcc.court,
lcc.county AS lcc_county,
ah.ACCOUNT,
ah.transaction_code,
ah.transaction_date,
ah.rule_id,
ah.amount,
ah.description,
r.state,
r.zip_code,
z.county AS ah_county,
z.county_2,
z.county_3,
z.county_4
FROM legal_address_skip las,
racctrel r,
ziplist z,
legal_court_cost lcc,
racctlgl rl,
legal_transaction_review ah
WHERE ah.ACCOUNT = rl.ACCOUNT
AND ah.ACCOUNT = las.ACCOUNT(+)
AND ah.ACCOUNT = r.ACCOUNT
AND nvl(lpad(substr(r.zip_code,0,instr(r.zip_code,'-')-1),5,0), substr(r.zip_code,1,5)) = z.zip
AND r.state = lcc.state
AND (REPLACE(lcc.county,' ','') = REPLACE(upper(z.county),' ','')
OR REPLACE(lcc.county,' ','') = REPLACE(upper(z.county_2),' ','')
OR REPLACE(lcc.county,' ','') = REPLACE(upper(z.county_3),' ','')
OR REPLACE(lcc.county,' ','') = REPLACE(upper(z.county_4),' ',''))
AND lcc.transaction_code = ah.transaction_code
AND lcc.transaction_code = 1
AND lcc.end_date IS NULL
AND ah.amount NOT BETWEEN lcc.cost_range_min AND lcc.cost_range_max
AND (account_amt NOT BETWEEN lcc.bal_range_min AND lcc.bal_range_max
OR lcc.bal_range_min - account_amt NOT BETWEEN 0 AND 500)
ORDER BY CASE
WHEN ah.amount NOT BETWEEN lcc.cost_range_min AND lcc.cost_range_max THEN 1
WHEN ah.amount BETWEEN lcc.cost_range_min AND lcc.cost_range_max THEN 2 END, ah.amount;
I've used aliases before in select statements so I'm confused on why I am getting an error for this. Does it work differently in this situation?
From the documentation (emphasis added):
You can use a column alias, c_alias, to label the immediately
preceding expression in the select list so that the column is
displayed with a new heading. The alias effectively renames the select
list item for the duration of the query. The alias can be used in the
ORDER BY clause, but not other clauses in the query.
So you can't refer to the alias in the where clause, where at the moment you have:
...
AND (account_amt NOT BETWEEN ...
...
The alias isn't valid at that point, so it's looking for a column with that name in one of the tables, and doesn't find one. It's fine in the order by though.
You either need to replace the alias with the repeated decode statement, or possibly use a subquery and then refer to the alias in a where clause in an outer query, but that might end up being less efficient depending on how selective your other conditions are.
Oracle runs the select query in the order below:
FROM clause
WHERE clause
GROUP BY clause
HAVING clause
SELECT clause
ORDER BY clause
Based on the above, you can see that when you are in the WHERE part, the alias has not yet been created. If you would like to use results from the SELECT part, you can do that by modifying your query like this:
WITH q AS
(
-- Your query without the extra AND
)
SELECT *
FROM q
WHERE --put your check here
This way you will already have the alias available when you reach the WHERE part.
Hope this helps! :)

#1111 - Invalid use of group function error in sql

Does anyone know a solution for this error:
#1111 - Invalid use of group function
This is my SQL:
SELECT leerlingen.leerlingnummer, voornaam, tussenvoegsel, achternaam, klas, leerlingen.bestemming
FROM betalingen, leerlingen, bestemmingen
WHERE leerlingen.leerlingnummer = betalingen.leerlingnummer AND SUM( betalingen.bedrag ) > bestemmingen.bedrag
GROUP BY leerlingen.leerlingnummer
You can't reference the results of an aggregate function (SUM) in predicated query (WHERE), you will have to specify the aggregate in the select, then use a "Having" clause to filter that set.

SQL server syntax error in update statement, but I can't see it

I'm getting a syntax error on this query, but I can't figure it out.
Incorrect syntax near the keyword
'group'.
I believe its on the last group by, but I don't see whats wrong. Can anyone suggest how to correct this?
UPDATE [NCLGS].[dbo].[CP_CustomerShipTo]
SET TimesUsed = TimesUsed + B.NewCount
from [NCLGS].[dbo].[CP_CustomerShipTo] CST
INNER JOIN (
Select
PKH.CompanyCode,
PKH.CompanyName,
PKH.Addr1,
PKH.Addr2,
PKH.City,
PKH.State,
PKH.Zip,
Count(recid) As NewCount
from avanti_packingslipheader PKH
where pksdate > dbo.ufn_StartOfDay(DATEADD(d, -1, GETDATE() ) )
group by
PKH.CompanyCode,
PKH.CompanyName,
PKH.Addr1,
PKH.Addr2,
PKH.City,
PKH.State,
PKH.Zip
) B
ON CST.CustomerCode = B.CompanyCode
AND CST.ShipToName = B.CompanyName
AND CST.ShipToAddress1 = B.Addr1
AND CST.City = B.City
AND CST.PostalCode = B.Zip
group by
PKH.CompanyCode,
PKH.CompanyName,
PKH.Addr1,
PKH.Addr2,
PKH.City,
PKH.State,
PKH.Zip
BACKGROUND - I'm trying to do an update statement with a Count(), but of course you can't use agg. functions in an update set statement, so I'm trying to use a subquery.
You have already got GROUP BY inside the subselect, so what does the outer GROUP BY stand for?
You can't reference an alias in a subselect from an outer GROUP BY. But in any event you can't use GROUP BY with an UPDATE statement, and that's what the error message is about.
Try removing the last Group By. What exactly are you hoping this last group by will do?
Change the code to this:
update mytable set
mycolumn = mycolumn + (select x from ...);