Raw query doesn't accept where condition with date - sql

I have this Raw query, but when I run it I get a sql syntax error.
here is the date params i use :
$last_week = Carbon::now()->subdays(7);
$last_2_week = Carbon::now()->subdays(14);
here is the query:
DB::raw("(SELECT SUM(vd.qty_available) FROM products AS P
JOIN variations AS V ON V.product_id=P.id
JOIN variation_location_details AS VD ON VD.variation_id=V.id
JOIN transaction_sell_lines as ts ON ts.variation_id=v.id
JOIN transactions as t ON ts.transaction_id=t.id
WHERE t.transaction_date>=$last_2_week) AS last_2_week_quantity"),
error :SQLSTATE[42000]: Syntax error or access violation: 1064

The actual SQL output will be similar to WHERE t.transaction_date >= 2020-01-01 00:00:00
which is invalid, you should wrap it in a single quotes.
something like
WHERE t.transaction_date>= '{$last_2_week}'
or better
WHERE t.transaction_date>= '{$last_2_week->toDateTimeString()}'
The toDateTimeString() forces the output to be in the correct format in this case.
or even better use the parameter binding
->whereRaw("... t.transaction_date>= ?", [$last_2_week->toDateTimeString()])

Put some space between the operand.
Instead of:
WHERE t.transaction_date>=$last_2_week) AS last_2_week_quantity")
Put:
WHERE t.transaction_date >= $last_2_week) AS last_2_week_quantity")

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

Excel Import VBA: Run-time 3075 Syntax error (missing operator) in query expression

I am getting a missing operator error in the following SQL statement:
SELECT Sample.Number, Sample.SampleDate, BOD.BOD_Concentration_IN, BOD.BOD_Concentration_OUT, TSS.TSS_Influent, TSS.TSS_Effluent
FROM SampleInformation as Sample
INNER JOIN BOD_Data as BOD ON Sample.Number = BOD.Number
INNER JOIN TSS_Data as TSS ON Sample.Number = TSS.Number
WHERE (DATEPART('m',Sample.SampleDate) = DATEPART('m',#1/13/2016 12:01:00 PM#))
AND (DATEPART('yyyy',Sample.SampleDate) = DATEPART('yyyy',#1/13/2016 12:01:00 PM#)) ORDER BY Sample.SampleDate
I eliminated the "WHERE" clause and still got the error, so it must be in the join.
Can anyone see what I am missing here? Thanks!
I finally figured out you are missing ( ) around the 'FROM' clause... try the following:
And BTW, 'Number' does not need to be enclosed in brackets (although it is a reserved word)
SELECT Sample.Number, Sample.SampleDate, BOD.BOD_Concentration_IN, BOD.BOD_Concentration_OUT, TSS.TSS_Influent, TSS.TSS_Effluent
FROM (SampleInformation AS Sample
INNER JOIN BOD_Data AS BOD ON Sample.Number = BOD.Number)
INNER JOIN TSS_Data AS TSS ON Sample.Number = TSS.Number
WHERE (DATEPART('m',Sample.SampleDate) = DATEPART('m',#1/13/2016 12:01:00 PM#))
AND (DATEPART('yyyy',Sample.SampleDate) = DATEPART('yyyy',#1/13/2016 12:01:00 PM#)) ORDER BY Sample.SampleDate

Missing Keyword ORA-00905

please tell me what is the syntax problem in this query
SELECT sde
FROM TABLE_EW sde , CASE_W spr, DOCUMENT swp
JOIN swp.id, swp.YEAR ON (swp.id = sde.ID_DOCUMENT)
JOIN spr.ID, spr.STATE, spr.NUMBER ON (spr.ID_DOCUMENT = swp.ID)
WHERE sde.IDENT_TABLEEW LIKE '122337456464'
AND swp.YEAR LIKE 2015;
SQLDeleoper point problem to From Line
I think this is the query you meant to write:
SELECT sde.*,swp.id, swp.YEAR,spr.ID, spr.STATE
FROM TABLE_EW sde
JOIN DOCUMENT swp ON (swp.id = sde.ID_DOCUMENT)
JOIN CASE_W spr ON (spr.ID_DOCUMENT = swp.ID)
WHERE sde.IDENT_TABLEEW = '122337456464'
AND swp.YEAR = 2015;
As mentioned in the comments, you have A LOT of errors in your SQL code.
You use implicit and explicit joins together, AVOID the use of implicit joins syntax and use only the proper syntax like my example.
Also, only in the select you can specify the columns you want, I'm guessing what you've been trying to do is
JOIN spr.ID, spr.STATE -> wanted this columns.
You should write them in the select part.
Another problem is the join condition, you either use implicit joins, (from table,table2,table3..) and then the join condition is in the where clause or you use explicit joins and then the condition is in the ON clause. You can't use both!
Another problem is the unnecessary use of LIKE . When comparing to an exact match, use EQUALS sign.

return value from nested sql

I have the following SQL and i want theorder_item_wo_id column to return null if the item does not exist in the nested sql and return the value of a column oi.cop_workorder_id if it does.
How can i accomplish this?
SELECT
cop.wo_id,
CASE
WHEN EXISTS (SELECT oi.cop_workorder_id
FROM oseo_orderitem oi
WHERE oi.cop_workorder_id = cop.wo_id) THEN
oi.cop_workorder_id
ELSE null
END AS order_item_wo_id
FROM oseo_cop_wo cop
where cop.wo_id = '123';
It looks like the oi.cop_workorder_id does not get recognized outside of the nested sql.
ERROR: missing FROM-clause entry for table "oi"
Unless I am missing something, it seems you are overcomplicating this.
Just use a LEFT JOIN:
SELECT
cop.wo_id,
oi.cop_workorder_id AS order_item_wo_id
FROM oseo_cop_wo AS cop
LEFT JOIN oseo_orderitem AS oi
ON oi.cop_workorder_id = cop.wo_id
WHERE cop.wo_id = '123';
use can use the COALESCE function. It works similar to Oracle's NVL function. I don't have PostgreSQL available to write and test this, however.

Converting MS Access Queries to PostgreSQL queries (format())

I have a query from MS Access SQL that I would like to execute in PostgreSQL:
SELECT Format("start_date", 'mmmm') AS "Month",
DFS_FIRE_ARCHIVE.FIRE_YEAR AS "Year",
Count(DFS_FIRE_ARCHIVE.FIRE_ZONE) AS "Number of Fires",
OBJECTIVES_NFD."response_category"
FROM (DFS_FIRE_ARCHIVE
INNER JOIN OBJECTIVE_ORDER ON DFS_FIRE_ARCHIVE.OBJECTIVE = OBJECTIVE_ORDER.OBJECTIVE)
INNER JOIN OBJECTIVES_NFD ON OBJECTIVE_ORDER.OBJECTIVE = OBJECTIVES_NFD.OBJECTIVE
GROUP BY Format("start_date",'mmmm'),
DFS_FIRE_ARCHIVE.FIRE_YEAR,
DFS_FIRE_ARCHIVE.OBJECTIVE,
Format("start_date",'mm'),
OBJECTIVE_ORDER.ORDER,
DFS_FIRE_ARCHIVE.FIRE_MGT_ZONE,
DFS_FIRE_ARCHIVE.FIRE_TYPE,
OBJECTIVES_NFD."response_category"
HAVING (((DFS_FIRE_ARCHIVE.FIRE_YEAR)=2009) AND ((DFS_FIRE_ARCHIVE.FIRE_MGT_ZONE)='INT') AND ((DFS_FIRE_ARCHIVE.FIRE_TYPE)='IFR'))
ORDER BY Format("start_date",'mm'), OBJECTIVE_ORDER.ORDER, DFS_FIRE_ARCHIVE.OBJECTIVE;
The error I am receiving is:
ERROR: function format(timestamp without time zone, unknown) does not exist
LINE 1: SELECT Format("start_date", 'mmmm') AS "Month",
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
Any help would be appreciated, thank-you.
The function you should replace Format with is probably to_char, e.g. to_char(timestamp, 'MM').
Take a look at PostgreSQL documentation:
http://www.postgresql.org/docs/9.0/static/functions-formatting.html
You are looking for to_char():
http://www.postgresql.org/docs/current/static/functions-formatting.html