One Line of Code Breaks Otherwise Working Query - sql

Everything in this query works just fine until I try to add the commented out portion (noted by '--') back into the query and run it. When I attempt to add the commented out WHERE clause back into the query body, it breaks the query. I have researched and experimented with adding the commented out line in different locations and in different ways, but nothing I have tried has worked so far.
SELECT
Count(DISTINCT a.acct_id),
CASE
WHEN b.user_seg = 'MTR' AND b.user_func = 'Sales' THEN 'MTR Sales'
WHEN b.user_seg = 'JMT' AND b.user_func = 'Sales' THEN 'JMT Sales'
THEN 'Partner Account Executive'
WHEN b.user_func IN ('Account Manager','Associate Account Manager','Outreach','Executive') THEN
'Customer Success'
WHEN b.user_func IN ('Relationship Manager') THEN 'Account Executive'
END AS sales_group
FROM qrs_access_views.mxp_sf_acct a
JOIN qrs_access_views.mxp_sf_user b
ON a.acc_crtd_by_id = b.user_id
AND a.is_sf_acct_del_y_n= 'n'
AND a.owner_id= '22573PAA3'
AND a.acct_mgr_user_id='22573PAA3'
AND b.user_seg <> '#'
--WHERE a.acc_crtd_date BETWEEN '2020-01-01' AND '2020-03-31'
LEFT JOIN grs_access_views.mxp_sf_user f
ON b.mgr_id = f.user_id
GROUP BY 2
When I run the query as above, I get a nice little grouped table kicked back to me by Teradata, but it is for all values for all time. (I just want to see the Q1 2020 numbers.)
When I add the commented out line back into the query I get some variation of the following error:
SELECT Failed. [3706] Syntax error: expected something between a string or a Unicode character literal and the 'LEFT' keyword.
Any help or assistance is greatly appreciated.

try this,
Instead of adding it to where clause use AND.
AND b.user_seg <> '#'
AND a.acc_crtd_date BETWEEN '2020-01-01' AND '2020-03-31'

Related

Assistance with Access ADP and/or SQL iif statement

I'm using Access ADP as a front end to SQL. I have two tables:
One is Price_2018
One is Price_2020
I want to choose Price from the Price_2018 or the Price_2020 table, depending upon the Purchase_Date. I tried first putting IiF statement in the Query Designer:
Iif ([Purchase_Date] < Convert(DateTime, '2020-01-01 00:00:00'),[Price_2018],[Price_2020])
Access didn't allow that and ended up putting the whole thing in quotes in the SQL pane, so all I got was text output.
Someone suggested putting in the Select section:
CASE ([Purchase_Date] < CONVERT(DATETIME, '2020-01-01 00:00:00') WHEN 1 THEN [Price_2018] ELSE [Price_2020]
That didn't work either and gave me this error:
Error in list of function arguments: '<' not recognized.Error in list of function arguments: ',' not recognized.Error in list of function arguments: 'FROM' not recognized.
Unable to parse query text.
How to resolve this error. I'm not familiar with using a CASE statement in Access or SQL.
I combined 2 Price tables (combined table called VWC_2018_2020) as suggested. Full query:
SELECT TOP 100 PERCENT dbo.VHCSERVER_Ntier_VHC_dbo_vwGenSvcInfo.Service_ID, dbo.VHCSERVER_Ntier_VHC_dbo_vwGenSvcInfo.Service_Date_From, dbo.VHCSERVER_Ntier_VHC_dbo_vwGenSvcInfo.Update_Status, dbo.VHCSERVER_Ntier_VHC_dbo_vwGenSvcInfo.Account_Number, dbo.VHCSERVER_Ntier_VHC_dbo_vwGenSvcInfo.Service_Units, dbo.VHCSERVER_Ntier_VHC_dbo_vwGenSvcInfo.Modifiers, dbo.VHCSERVER_Ntier_VHC_dbo_vwGenSvcInfo.Procedure_Code, NormalUnionCPASumAdjustments.SumAmount AS Adjustment, NormalUnionCPASumPayments.SumAmount AS Payment, dbo.VHCSERVER_Ntier_VHC_dbo_vwGenSvcInfo.Service_Fee AS Charge, dbo.VHCSERVER_Ntier_VHC_dbo_vwGenSvcInfo.Service_Fee - ISNULL(NormalUnionCPASumPayments.SumAmount, 0) AS Unpaid, dbo.VHCSERVER_Ntier_VHC_dbo_vwGenSvcInfo.Primary_Diagnosis_Code, LastInsurancePmt.last_insurance_pmt, dbo.VHCSERVER_Ntier_VHC_dbo_vwGenSvcInfo.Patient_Number, dbo.VWCFees_2018_2020.VWC_2020, dbo.VWCFees_2018_2020.VWC_2018, IIF (dbo.VHCSERVER_Ntier_VHC_dbo_vwGenSvcInfo.Service_Date_From < CDate('2020-01-01 00:00:00'),dbo.VWCFees_2018_2020.VWC_2018,dbo.VWCFees_2018_2020.VWC_2020) AS VWCFEE
FROM dbo.VHCSERVER_Ntier_VHC_dbo_vwGenSvcInfo LEFT OUTER JOIN dbo.VWCFees_2018_2020 ON dbo.VHCSERVER_Ntier_VHC_dbo_vwGenSvcInfo.Procedure_Code = dbo.VWCFees_2018_2020.CPT LEFT OUTER JOIN dbo.NormalUnionCPASumAdjustments() NormalUnionCPASumAdjustments ON dbo.VHCSERVER_Ntier_VHC_dbo_vwGenSvcInfo.Service_ID = NormalUnionCPASumAdjustments.Service_ID LEFT OUTER JOIN dbo.NormalUnionCPASumPayments() NormalUnionCPASumPayments ON dbo.VHCSERVER_Ntier_VHC_dbo_vwGenSvcInfo.Service_ID = NormalUnionCPASumPayments.Service_ID LEFT OUTER JOIN dbo.LastInsurancePmt() LastInsurancePmt ON dbo.VHCSERVER_Ntier_VHC_dbo_vwGenSvcInfo.Service_ID = LastInsurancePmt.Service_ID
WHERE (dbo.VHCSERVER_Ntier_VHC_dbo_vwGenSvcInfo.Update_Status <= 1) AND (dbo.VHCSERVER_Ntier_VHC_dbo_vwGenSvcInfo.Service_Date_From BETWEEN #StartDate AND #EndDate) AND (dbo.VHCSERVER_Ntier_VHC_dbo_vwGenSvcInfo.Patient_Number = #VHC_NumberChild)
Running in Access, gives error message: '<' not recognized. Missing FROM clause. Unable to parse query text.
What now? Thanks
Since ADP files use an SQL Server backend (no longer supported as of MS Access 2013), you must use its TSQL dialect which does support IIF (or CASE) and can compare dates with string representations without conversion.
Below I extend to fuller query assuming various columns. Adjust as needed:
SELECT
...
IIF(t.[Purchase_Date] < '2020-01-01', p18.price, p20.price)
...
FROM [Transactions] t
INNER JOIN [Price_2018] p18
ON t.price_id = p18.price_id
INNER JOIN [Price_2020] p20
ON t.price_id = p20.price_id

Issue With SQL Pivot Function

I have a SQL query where I am trying to replace null results with zero. My code is producing an error
[1]: ORA-00923: FROM keyword not found where expected
I am using an Oracle Database.
Select service_sub_type_descr,
nvl('Single-occupancy',0) as 'Single-occupancy',
nvl('Multi-occupancy',0) as 'Multi-occupancy'
From
(select s.service_sub_type_descr as service_sub_type_descr, ch.claim_id,nvl(ci.item_paid_amt,0) as item_paid_amt
from table_1 ch, table_" ci, table_3 s, table_4 ppd
where ch.claim_id = ci.claim_id and ci.service_type_id = s.service_type_id
and ci.service_sub_type_id = s.service_sub_type_id and ch.policy_no = ppd.policy_no)
Pivot (
count(distinct claim_id), sum(item_paid_amt) as paid_amount For service_sub_type_descr IN ('Single-occupancy', 'Multi-occupancy')
)
This expression:
nvl('Single-occupancy',0) as 'Single-occupancy',
is using an Oracle bespoke function to say: If the value of the string Single-occupancy' is not null then return the number 0.
That logic doesn't really make sense. The string value is never null. And, the return value is sometimes a string and sometimes a number. This should generate a type-conversion error, because the first value cannot be converted to a number.
I think you intend:
coalesce("Single-occupancy", 0) as "Single-occupancy",
The double quotes are used to quote identifiers, so this refers to the column called Single-occupancy.
All that said, fix your data model. Don't have identifiers that need to be quoted. You might not have control in the source data but you definitely have control within your query:
coalesce("Single-occupancy", 0) as Single_occupancy,
EDIT:
Just write the query using conditional aggregation and proper JOINs:
select s.service_sub_type_descr, ch.claim_id,
sum(case when service_sub_type_descr = 'Single-occupancy' then item_paid_amt else 0 end) as single_occupancy,
sum(case when service_sub_type_descr = 'Multi-occupancy' then item_paid_amt else 0 end) as multi_occupancy
from table_1 ch join
table_" ci
on ch.claim_id = ci.claim_id join
table_3 s
on ci.service_type_id = s.service_type_id join
table_4 ppd
on ch.policy_no = ppd.policy_no
group by s.service_sub_type_descr, ch.claim_id;
Much simpler in my opinion.
for column aliases, you have to use double quotes !
don't use
as 'Single-occupancy'
but :
as "Single-occupancy",

SQL Developer 'run script' failing but 'run statement' works

I have a simple left join query on two tables linking to get the description:
SELECT WORK.ACTION_ID, WORK.ACTION_STAT, WORK.DESCRIPTION_ID,
WORK.CLIENT_SERVER_IND, WORK.UPDATE_TSTAMP, WORK.UPDATE_USER_ID,
WORK.OTHER_ACTION_DATA, D.DESCRIPTION_ID, D.LANGUAGE, D.DESCRIPTION_TEXT,
D.UPDATE_TSTAMP DSCRP_UPD_TSTAMP
FROM xxxx.R_ACTION WORK
INNER JOIN xxxx.R_DESC_TEXT D ON WORK.DESCRIPTION_ID = D.DESCRIPTION_ID
WHERE D.LANGUAGE = 'ENGLISH'
AND D.DESCRIPTION_STAT = 'P';
I have the query in SQL Developer and if I select 'Run Statement' it works fine in less than a second and I can retrieve all 283 records.
If I select 'Run Script' I can see the output for about 33 lines and it then just hangs and eventually I get a 'socket read timed out' message.
I have the same table in a different schema, but with slight different data in it, and in that one the run statement and run script work fine.
Why would it work for 'Run Statement' but fail for 'Run Script' in this schema?
I'm on the CLOB bandwagon, too. Thinking 90% chance your DESCRIPTION_TEXT is a CLOB field.
As a test, try this query as "run script", which ignores the actual DESCRIPTION_TEXT and outputs "bogus" instead:
SELECT WORK.ACTION_ID, WORK.ACTION_STAT, WORK.DESCRIPTION_ID,
WORK.CLIENT_SERVER_IND, WORK.UPDATE_TSTAMP, WORK.UPDATE_USER_ID,
WORK.OTHER_ACTION_DATA, D.DESCRIPTION_ID, D.LANGUAGE, 'bogus' DESCRIPTION_TEXT,
D.UPDATE_TSTAMP DSCRP_UPD_TSTAMP
FROM xxxx.R_ACTION WORK
INNER JOIN xxxx.R_DESC_TEXT D ON WORK.DESCRIPTION_ID = D.DESCRIPTION_ID
WHERE D.LANGUAGE = 'ENGLISH'
AND D.DESCRIPTION_STAT = 'P';
If that works, try using this query, which makes use of DBMS_LOB.SUBSTR() to help cast the CLOB as VARCHAR by truncating output to first 4000 characters of it.
SELECT WORK.ACTION_ID, WORK.ACTION_STAT, WORK.DESCRIPTION_ID,
WORK.CLIENT_SERVER_IND, WORK.UPDATE_TSTAMP, WORK.UPDATE_USER_ID,
WORK.OTHER_ACTION_DATA, D.DESCRIPTION_ID, D.LANGUAGE,
dbms_lob.substr(D.DESCRIPTION_TEXT, 4000) DESCRIPTION_TEXT,
D.UPDATE_TSTAMP DSCRP_UPD_TSTAMP
FROM xxxx.R_ACTION WORK
INNER JOIN xxxx.R_DESC_TEXT D ON WORK.DESCRIPTION_ID = D.DESCRIPTION_ID
WHERE D.LANGUAGE = 'ENGLISH'
AND D.DESCRIPTION_STAT = 'P';

Use Case Statement in Join

Hi every one i want to use case statement in join using this query and got error
Select CONVERT(VARCHAR(10), SII.SIDATE,103)DATE,SII.SALEID,SII.ItemName,SI.TenancyID
FROM F_SALESINVOICEITEM SII
INNER JOIN F_SALESINVOICE SI ON SI.SALEID=SII.SALEID
INNER JOIN #TempTableSearch ts ON CASE
WHEN ts.ACCOUNTTYPE = '1' THEN ts.ACCOUNTID=SI.TENANCYID
WHEN ts.ACCOUNTTYPE='2' THEN ts.ACCOUNTID=SI.EMPLOYEEID
WHEN ts.ACCOUNTTYPE='3' THEN ts.ACCOUNTID=SI.SUPPLIERID
WHEN ts.ACCOUNTTYPE='4' THEN ts.ACCOUNTID=SI.SALESCUSTOMERID
Error
Incorrect syntax near '='.
Please help me to solve this error.
IT should be,
ON
ts.ACCOUNTID = CASE
WHEN ts.ACCOUNTTYPE = '1' THEN SI.TENANCYID
WHEN ts.ACCOUNTTYPE = '2' THEN SI.EMPLOYEEID
WHEN ts.ACCOUNTTYPE = '3' THEN SI.SUPPLIERID
WHEN ts.ACCOUNTTYPE = '4' THEN SI.SALESCUSTOMERID
END
Instead of using CASE, I'd much rather do this:
Select CONVERT(VARCHAR(10), SII.SIDATE,103)DATE,SII.SALEID,SII.ItemName,SI.TenancyID
FROM F_SALESINVOICEITEM SII
INNER JOIN F_SALESINVOICE SI ON SI.SALEID=SII.SALEID
INNER JOIN #TempTableSearch ts ON
(ts.ACCOUNTTYPE='1' AND ts.ACCOUNTID=SI.TENANCYID)
OR (ts.ACCOUNTTYPE='2' AND ts.ACCOUNTID=SI.EMPLOYEEID)
OR (ts.ACCOUNTTYPE='3' AND ts.ACCOUNTID=SI.SUPPLIERID)
OR (ts.ACCOUNTTYPE='4' AND ts.ACCOUNTID=SI.SALESCUSTOMERID)
To explain why the query didn't work for you: the syntax of the CASE requires an END at the end of the clause. It would work, as the other solutions proposed suggest, but I find this version to be more convenient to understand - although this part is highly subjective.
you can do this, so you have no chance to misspell something (note that ACCOUNTTYPE and ACCOUNTID used only when needed, you don't have to copy-paste it)
select
convert(varchar(10), SII.SIDATE,103) as DATE,
SII.SALEID, SII.ItemName, SI.TenancyID
from F_SALESINVOICEITEM as SII
inner join F_SALESINVOICE as SI on SI.SALEID = SII.SALEID
outer apply (
'1', SI.TENANCYID
'2', SI.EMPLOYEEID
'3', SI.SUPPLIERID
'4', SI.SALESCUSTOMERID
) as C(ACCOUNTTYPE, ACCOUNTID)
inner join #TempTableSearch as ts on
ts.ACCOUNTTYPE = C.ACCOUNTTYPE and ts.ACCOUNTID = C.ACCOUNTID
You have syntax error. You are missing END there.
You must understand that CASE ... END block is NOT equivalent to IF { } from C-like languages. Much rather this is equivalent to elaborate version of ... ? ... : ... operator from C-like languages. What it means that the WHOLE CASE block must essentially evaluate to single value and that this value has to be the same type no matter which case of the block is executed. This means that:
CASE
WHEN ts.ACCOUNTTYPE = '1' THEN ts.ACCOUNTID=SI.TENANCYID ...
END
Is fundamentally incorrect unless you work on a version of database that will allow you bool value as a value (SQL Server won't allow it for example but I think some of MySQL version used to allow it - not sure about this). You probably should write something like:
CASE
WHEN ts.ACCOUNTTYPE = '1' AND ts.ACCOUNTID=SI.TENANCYID THEN 1
WHEN ts.ACCOUNTTYPE='2' AND ts.ACCOUNTID=SI.EMPLOYEEID THEN 1
WHEN ts.ACCOUNTTYPE='3' AND ts.ACCOUNTID=SI.SUPPLIERID THEN 1
WHEN ts.ACCOUNTTYPE='4' AND ts.ACCOUNTID=SI.SALESCUSTOMERID THEN 1
ELSE 0
END = 1
Notice how the whole CASE block evaluates to 1 or 0 and then it is compared to 1. Of course instead of 4 WHEN's you could use one WHEN with combination of AND's, OR's and ( ) brackets. Of course in this particular case answer by #ppeterka 66 is correct as CASE is not suited for what you really wanted to do - I'm just trying to clarify what CASE really is.

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#)