SQL Developer: invalid identifier error - sql

This is the part of my query that has error:
, case when dsi.distributor_id in
('ALBQA','ASGLA','ASGNY','ASGR1','ASGSF','BIKU9','COAUU','CSWHP','DPIB1','DPID9',
'DPISP','DPISQ','EAS3X','GEP79','GRG8V','NACY7','NOSYK','ORGK7','PETR1','TOP0U',
'UNFIA','UNFIL','UNFIQ','UNFIS','UNMQ9','KOSI8','KEHEN','CSNYC','ALBQA','ALC6Y','BAM7D','BIKU9','CLCE0','COAUU','CSWHT','EAS3X','FOUXU','GEP79',
'GRG8V','HED9Q','LAOJD','MCLFS','NOSYK','ORGK7','UNMQ9','OMAH1'
)
then 'Distributor'
else 'Direct'
end as is_direct
, SUM(dsi.cost) AS tot_cost
, SUM(CASE WHEN is_direct = 'Direct' THEN dsi.cost ELSE 0 END ) AS Direct_cost
It says that is_direct is an invalid column but I already indicated it above. Therefore, I was wondering if you could help me find where I went wrong.

Columns defined in your query cannot be used in other places in your query, whether it is in other columns, or WHERE clauses, etc.
I would suggest either placing these calculations into subqueries, or using WITH AS.

Related

SQL Sub-query parameters from Excel

I have SQL query with a sub-query where I want to assign sub query parameters from a cell in an Excel sheet, as this query cant be represented graphically Excel keep throwing error on this:
[Microsoft][ODBC SQL Server Driver] Invalid paramter number and
[Microsoft][ODBC SQL Server Driver] Invalid Descriptor Index
I have already tried solution as mentioned here to trick excel without success Using Parameters in SQL query with sub-query
;WITH dataset_bl as (
SELECT
--rank() over (partition by date_of_AC, ac_room order by into_theatre) as OrderNumber
--,datetime_of_AC as booking_datetime
date_of_AC
,AC_room
,specialty
,OAMRN
,substring(Subject_NAME,1,CHARINDEX(' ',Subject_NAME,1)) as 'surname'
,substring(Subject_NAME,CHARINDEX(' ',Subject_NAME,1)+2,500) as 'forename'
,convert(date,[dttm_of_birth],103) as DOB
,PRIN_SO as 'surg'
,'"'+ASST_SO_1+' '+ASST_SO_2+'"' as 'assistant_SO'
,substring(CONSULT_NAME,1,abs(CHARINDEX(',',CONSULT_NAME,1)-1)) as 'consult_surname'
,substring(CONSULT_NAME,CHARINDEX(' ',CONSULT_NAME,1)+1,500) as 'consult_first_name'
,'"'+actual_AC+'"' as AC_details
,'"'+PLANNED_PROD+'"' as booked_details
,'Carried Out' as 'TT_outcome'
, 'NULL' as 'unP_return_flag'
,OP_type
--,LOS
,case when CL_PRIORITY ='' then 'Not listed' else 'isted' end as islisted
,CLI_PRIORITY as listed_priority
,case when EM_PRIORITY like '<=%' then 'Submitted' else 'No Greensheet' end as isGreensheet
,em_priority as a, case when EM_PRIORITY like '<=%' and em_priority <> '<=72hrsCannot charge before prod'then LEFT(EM_PRIORITY, abs(charindex('-',EM_PRIORITY)-1))
when em_priority = '<=72hrsCannot diso before prod' then '<=72hrs' else 'NULL' end as em_priority
FROM sample.dbo.tb_Fnl_Sur_th4 WITH (NOLOCK)
**WHERE main_ident = 'A224' and convert(date,into_Start, 103) >= '2019-07-01' and convert(date,into_Start, 103) <= '2019-07-31'** --i am trying to get these parameters from excel cell value
)
SELECT * FROM dataset_bl
WHERE specialty like 'abc%'
or (consult_surname like '%abc%' and consult_first_name like '%def%' )
or surg in ('cde,fghi',
'jkl,'mnop,
'qrs,Tuv')
order by convert(date,date_of_procedure,103), operating_room--, into_theatre
Here's some suggestion.
First is to check the formatting of your date columns.
and build your parameter to be like
Cast(into_Start as smalldatetime) between ? and ?
I've been on that same issue and seem to find the solution for me. In fact the parameter [?] use in MSQUERY in Excel will normally work when you have a direct Query
Ex:
Select [YourTable].[Column]
From [YourTable]
Where [YourTable].[Column]= ?
The Excel parameter will prompt and trigger where the windows that ask you which cell or Data you want that parameter have to be filled with.
In the other hand if you use the a Subquery and you add a Where condition with the Parameter ? will be stuck with the parameter [Microsoft][ODBC SQL Server Driver] Invalid paramter number and [Microsoft][ODBC SQL Server Driver] Invalid Descriptor Index
If you download the ODBC Driver for SQL Server here -->
https://www.microsoft.com/fr-fr/download/details.aspx?id=56567
Install it and make sure that the ODBC use for your MSQUERY in Excel use that connection.
ODBC Data Source to use
After this I was able to use a MSQuery in Excel using Parameter like this one
Select [RenamedTable].*
From (Select [YourTable].[Column1],
[YourTable].[Column2],
[YourTable].[Column3]
From [YourTable]) as RenamedTable
Where [RenamedTable].[Column1] between ? and ?
Hope this will work for you as for me because I had similar problem with between date Parameter

Dreaded "Missing Right Parenthesis" Error in Oracle SQL

We access an Oracle database through a web application. The web application is published, hosted and administered off-site. One component of the web application are dashboards, which use SQL to return data from the system on regular intervals that are then displayed and can trigger alarms should certain thresholds be reached.
The SQL has several parameters that are assigned in the dashboard setup: LOCATION, OWNER_DEPT, USING_DEPT and DAYS_AHEAD and appear to be working properly. Here is the query:
SELECT * FROM
(
SELECT DISTINCT
"MFIVE"."VIEW_WORK_REQ_OCC"."UNIT_NO" AS "UNIT NO", "MFIVE"."VIEW_WORK_REQ_OCC"."WORK_REQ_NO" AS "WORK REQ NO", "MFIVE"."VIEW_WORK_REQ_OCC"."JOB" AS "JOB",
CASE WHEN "MFIVE"."VIEW_WORK_REQ_OCC"."DUE_DATE" IS NULL THEN NULL ELSE ("MFIVE"."VIEW_WORK_REQ_OCC"."DUE_DATE") END AS "DUE DATE",
CASE WHEN "MFIVE"."VIEW_WORK_REQ_OCC"."FIRST_DATE" IS NULL THEN NULL ELSE ("MFIVE"."VIEW_WORK_REQ_OCC"."FIRST_DATE") END AS "FIRST DATE",
CASE WHEN "MFIVE"."VIEW_WORK_REQ_OCC"."LAST_DATE" IS NULL THEN NULL ELSE ("MFIVE"."VIEW_WORK_REQ_OCC"."LAST_DATE") END AS "LAST DATE"
FROM "MFIVE"."VIEW_WORK_REQ_OCC"
WHERE
("MFIVE"."VIEW_WORK_REQ_OCC"."MNT_PREVENTIVE_FL" = 'Y') AND
(UPPER("MFIVE"."VIEW_WORK_REQ_OCC"."LOCATION") LIKE UPPER(CONCAT(CONCAT('%', ':<LOCATION>'), '%'))) AND
(UPPER("MFIVE"."VIEW_WORK_REQ_OCC"."OWNER_DEPT") LIKE UPPER(CONCAT(CONCAT('%', ':<OWNER_DEPT>'), '%'))) AND
(UPPER("MFIVE"."VIEW_WORK_REQ_OCC"."USING_DEPT") LIKE UPPER(CONCAT(CONCAT('%', ':<USING_DEPT>'), '%'))) AND
("MFIVE"."VIEW_WORK_REQ_OCC"."DUE_DATE" >= SYSDATE + ':<DAYS_AHEAD>')
ORDER BY
"MFIVE"."VIEW_WORK_REQ_OCC"."UNIT_NO" ASC,
"MFIVE"."VIEW_WORK_REQ_OCC"."JOB" ASC,
CASE WHEN "MFIVE"."VIEW_WORK_REQ_OCC"."DUE_DATE" IS NULL THEN NULL ELSE ("MFIVE"."VIEW_WORK_REQ_OCC"."DUE_DATE") END AS "DUE DATE" ASC
)
The issue is with the statements involving "MFIVE"."VIEW_WORK_REQ_OCC"."DUE_DATE". We're attempting to return only values where DUE_DATE is greater than the SYSDATE plus the value in the DAYS_AHEAD parameter. Deleting these lines allows the query to execute properly; leaving them as-is returns the error ORA-00907: missing right parenthesis.
The majority of the SQL was lifted from the SQL as generated by an ad-hoc reporting component of the web application. The report runs properly, but we are not able to pass parameters through the ad-hoc reporting module. The modifications to the original were to add the bind variables.
I'm hoping someone can point me in the correct direction to remedy this issue. Any assistance is appreciated.
Thanks to Kaushik Nayak for helping me see the forest for the trees.
The correction only affects the ORDER BY clause:
...
ORDER BY
"MFIVE"."VIEW_WORK_REQ_OCC"."UNIT_NO" ASC,
"MFIVE"."VIEW_WORK_REQ_OCC"."JOB" ASC,
)

"Circular reference caused by ..." error in Access SQL (but not in T-SQL)

I have the following SQL statement which returns the desired result in SQL Server 2012:
SELECT
S.ONOMA
, S.DIEY
, S.POLH
, S.TK
, S.IDIOT
, S.KODIKOS
, S.AFM
FROM
SYNERG AS S
INNER JOIN
(SELECT
G.AFM, MIN(KODIKOS) AS KODIKOS
FROM SYNERG AS G
WHERE LEN(ISNULL(AFM, '')) != 0
GROUP BY AFM) AS I ON S.KODIKOS = I.KODIKOS
ORDER BY
S.AFM
but when I run the same SQL statement in MS Access 2007 I get an error:
Circular reference caused by 'KODIKOS' in query definition's SELECT list.
Any help would be appreciated.
As explained in the link by HansUp:
The alias of a calculated field cannot be identical to any of the field names used to calculate the field.
This can be rather annoying (esp. if it is a field that is returned by the query), but there is no way around it.
So you need to change the alias, e.g.:
SELECT
S.ONOMA
, S.DIEY
, S.POLH
, S.TK
, S.IDIOT
, S.KODIKOS
, S.AFM
FROM
SYNERG AS S
INNER JOIN
(SELECT
G.AFM, MIN(KODIKOS) AS MinKODIKOS
FROM SYNERG AS G
WHERE LEN(Nz(AFM, '')) <> 0
GROUP BY AFM) AS I ON S.KODIKOS = I.MinKODIKOS
ORDER BY
S.AFM
Note also that an IsNull() function exists in Access, but has a different meaning (it takes one argument and returns a Boolean). The corresponding function is Nz()
And (thanks #HansUp), the unequal operator is <>, not !=. I always use <> in SQL Server too, no need to make things more complicated than necessary. :)

How can I use CASE expression with SUM function in SQL?

I have an Oracle SQL query that I need to select certain deduction codes and provide a predetermined amount if based on the premium amount for deduction code 91B. These are hard coded values that I need to summarize.
SELECT SUM(DECODE(DEDCD,'91A',AL_AMOUNT,0)) MED91A,
SUM(CASE WHEN DEDCD = '91B' THEN
DECODE(AL_AMOUNT, 23.54,7.85,
40.62,8.31,
43.85,8.31,
56.77,8.31,
AL_AMOUNT)) MED91B
FROM PS_AL_CHK_DED
WHERE WEEK_NBR = 6
AND TO_CHAR(CHECK_DT, 'YYYY')=TO_CHAR(SYSDATE, 'YYYY')
The SUM(DECODE ..) statement used to summarize values where dedcd = '91A' works fine. When I add the part to summarize values where dedcd = '91B' it produces a 'Missing Keyword' error after the decode statement. I'm trying to streamline the query in order to produce the results I need for these two deduction codes because the full query takes entirely too long to run.
Oracle Sql Developer 4.0.2.15
You must complete the case expression syntax with an END keyword.
Do it like this:
CASE WHEN DEDCD = '91B' THEN
DECODE(AL_AMOUNT, 23.54,7.85,
40.62,8.31,
43.85,8.31,
56.77,8.31,
AL_AMOUNT)
END
A basic case expression looks like:
CASE [ expression ]
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
WHEN condition_n THEN result_n
ELSE result
END
See the documentation for more details.

Comparing Date Values in Access - Data Type Mismatch in Criteria Expression

i'm having an issue comparing a date in an access database. basically i'm parsing out a date from a text field, then trying to compare that date to another to only pull newer/older records.
so far i have everything working, but when i try to add the expression to the where clause, it's acting like it's not a date value.
here's the full SQL:
SELECT
Switch(Isdate(TRIM(LEFT(bc_testingtickets.notes, Instr(bc_testingtickets.notes, ' ')))) = false, 'NOT ASSIGNED!!!') AS [Assigned Status],
TRIM(LEFT(bc_testingtickets.notes, Instr(bc_testingtickets.notes, ' '))) AS [Last Updated Date],
bc_testingtickets.notes AS [Work Diary],
bc_testingtickets.ticket_id,
clients.client_code,
bc_profilemain.SYSTEM,
list_picklists.TEXT,
list_picklists_1.TEXT,
list_picklists_2.TEXT,
list_picklists_3.TEXT,
bc_testingtickets.createdate,
bc_testingtickets.completedate,
Datevalue(TRIM(LEFT([bc_TestingTickets].[notes], Instr([bc_TestingTickets].[notes], ' ')))) AS datetest
FROM list_picklists AS list_picklists_3
RIGHT JOIN (list_picklists AS list_picklists_2
RIGHT JOIN (list_picklists AS list_picklists_1
RIGHT JOIN (bc_profilemain
RIGHT JOIN (((bc_testingtickets
LEFT JOIN clients
ON
bc_testingtickets.broker = clients.client_id)
LEFT JOIN list_picklists
ON
bc_testingtickets.status = list_picklists.id)
LEFT JOIN bc_profile2ticketmapping
ON bc_testingtickets.ticket_id =
bc_profile2ticketmapping.ticket_id)
ON bc_profilemain.id =
bc_profile2ticketmapping.profile_id)
ON list_picklists_1.id = bc_testingtickets.purpose)
ON list_picklists_2.id = bc_profilemain.destination)
ON list_picklists_3.id = bc_profilemain.security_type
WHERE ( ( ( list_picklists.TEXT ) <> 'Passed'
AND ( list_picklists.TEXT ) <> 'Failed'
AND ( list_picklists.TEXT ) <> 'Rejected' )
AND ( ( bc_testingtickets.ticket_id ) <> 4386 ) )
GROUP BY bc_testingtickets.notes,
bc_testingtickets.ticket_id,
clients.client_code,
bc_profilemain.SYSTEM,
list_picklists.TEXT,
list_picklists_1.TEXT,
list_picklists_2.TEXT,
list_picklists_3.TEXT,
bc_testingtickets.createdate,
bc_testingtickets.completedate,
DateValue(TRIM(LEFT([bc_TestingTickets].[notes], Instr([bc_TestingTickets].[notes], ' '))))
ORDER BY Datevalue(TRIM(LEFT([bc_TestingTickets].[notes], Instr([bc_TestingTickets].[notes], ' '))));
the value i'm trying to compare against a various date is this:
DateValue(Trim(Left([bc_TestingTickets].[notes],InStr([bc_TestingTickets].[notes],' '))))
if i add a section to the where clause like below, i get the Data Type Mismatch error:
WHERE DateValue(Trim(Left([bc_TestingTickets].[notes],InStr([bc_TestingTickets].[notes],' ')))) > #4/1/2012#
i've even tried using the DateValue function around the manual date i'm testing with but i still get the mismatch error:
WHERE DateValue(Trim(Left([bc_TestingTickets].[notes],InStr([bc_TestingTickets].[notes],' ')))) > DateValue("4/1/2012")
any tips on how i can compare a date in this method? i can't change any fields in the database, ect, that's why i'm parsing the date in SQL and trying to manipulate it so i can run reports against it.
i've tried googling but nothing specifically talks about parsing a date from text and converting it to a date object. i think it may be a bug or the way the date is being returned from the left/trim functions. you can see i've added a column to the end of the SELECT statement called DateTest and it's obvious access is treating it like a date (when the query is run, it asks to sort by oldest to newest/newest to oldest instead of A-Z or Z-A), unlike the second column in the select.
thanks in advance for any tips/clues on how i can query based on the date.
edit:
i just tried the following statements in my where clause and still getting a mismatch:
CDate(Trim(Left([bc_TestingTickets].[notes],InStr([bc_TestingTickets].[notes],' ')))) > #4/1/2012#
CDate(Trim(Left([bc_TestingTickets].[notes],InStr([bc_TestingTickets].[notes],' ')))) >
CDate("4/1/2012") CDate(DateValue(Trim(Left([bc_TestingTickets].[notes],InStr([bc_TestingTickets].[‌​notes],' '))))) > #4/1/2012#
i tried with all the various combinations i could think of regarding putting CDate inside of DateValue, outside, ect. the CDate function does look like what i should be using though. not sure why it's still throwing the error.
here's a link to a screenshot showing the results of the query http://ramonecung.com/access.jpg. there's two screenshots in one image.
You reported you get Data Type Mismatch error with this WHERE clause.
WHERE DateValue(Trim(Left([bc_TestingTickets].[notes],
InStr([bc_TestingTickets].[notes],' ')))) > #4/1/2012#
That makes me wonder whether [bc_TestingTickets].[notes] can ever be Null, either because the table design allows Null for that field, or Nulls are prohibited by the design but are present in the query's set of candidate rows as the result of a LEFT or RIGHT JOIN.
If Nulls are present, your situation may be similar to this simple query which also triggers the data type mismatch error:
SELECT DateValue(Trim(Left(Null,InStr(Null,' '))));
If that proves to be the cause of your problem, you will have to design around it somehow. I can't offer a suggestion about how you should do that. Trying to analyze your query scared me away. :-(
It seems like you are having a problem with the type conversion. In this case, I believe that you are looking for the CDate function.
A problem might be the order of the date parts. A test in the Immediate window shows this
?cdate(#4/1/2012#)
01.04.2012
?cdate(#2012/1/4#)
04.01.2012
Write the dates backwards in the format yyyy/MM/dd and thus avoiding inadverted swapping of days and months!
DateValue("2012/1/4")
and
CDate(#2012/1/4#)