SQL Syntax error. Where is my syntatic mistake? - mysql

I can't for the life of me spot my typo!
UPDATE orders o, orders_total_couponz otc
SET o.total_paid = o.total_paid - ( otc.converted_value * ( 1 + ( otc.tax_rate / 100 ) ) ),
SET o.total_paid_tax_incl = o.total_paid_tax_incl - ( otc.converted_value * ( 1 + ( otc.tax_rate / 100 ) ) ),
SET o.total_paid_tax_excl = o.total_paid_tax_excl - otc.converted_value,
SET o.total_paid_tax_real = o.total_paid_tax_real - ( otc.converted_value * ( 1 + ( otc.tax_rate / 100 ) ) ),
SET o.total_products = o.total_products - otc.converted_value,
SET o.total_products_wt = o.total_products_wt - ( otc.converted_value * ( 1 + ( otc.tax_rate / 100 ) ) )
WHERE o.id_order = otc.orders_id
error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET o.total_paid_tax_incl = o.total_paid_tax_incl - ( otc.converted_value * ( 1 ' at line 3

Use the set keyword only once, and comma-separate the values to set:
UPDATE orders o, orders_total_couponz otc
SET o.total_paid = o.total_paid - ( otc.converted_value * ( 1 + ( otc.tax_rate / 100 ) ) ),
o.total_paid_tax_incl = o.total_paid_tax_incl - ( otc.converted_value * ( 1 + ( otc.tax_rate / 100 ) ) ),
o.total_paid_tax_excl = o.total_paid_tax_excl - otc.converted_value,
o.total_paid_tax_real = o.total_paid_tax_real - ( otc.converted_value * ( 1 + ( otc.tax_rate / 100 ) ) ),
o.total_products = o.total_products - otc.converted_value,
o.total_products_wt = o.total_products_wt - ( otc.converted_value * ( 1 + ( otc.tax_rate / 100 ) ) )
WHERE o.id_order = otc.orders_id

Do not use SET again and again. Use command like:
UPDATE orders o, orders_total_couponz otc
SET o.total_paid = o.total_paid - ( otc.converted_value * ( 1 + ( otc.tax_rate / 100 ) ) ),
o.total_paid_tax_incl = o.total_paid_tax_incl - ( otc.converted_value * ( 1 + ( otc.tax_rate / 100 ) ) ),
o.total_paid_tax_excl = o.total_paid_tax_excl - otc.converted_value,
o.total_paid_tax_real = o.total_paid_tax_real - ( otc.converted_value * ( 1 + ( otc.tax_rate / 100 ) ) ),
o.total_products = o.total_products - otc.converted_value,
o.total_products_wt = o.total_products_wt - ( otc.converted_value * ( 1 + ( otc.tax_rate / 100 ) ) )
WHERE o.id_order = otc.orders_id

Related

Snowflake Function input is datetime, but when i call the function it's not quite working

with temp AS (
SELECT CAST(SUM(sreg.ScrapQuantity) AS INT) AS Quantity,
sreas.Name AS ScrapReason,
to_date((DATEADD(MINUTE, 30 * (DATE_PART(MINUTE, sreg.ScrapTime) / 30), DATEADD(HOUR, TIMESTAMPDIFF(HOUR, '0', sreg.ScrapTime), '0')))) AS DATETIME,
sreg.EquipmentID AS EquipmentID
FROM ScrapRegistration sreg
INNER JOIN ScrapReason sreas ON sreas.ID = sreg.ScrapReasonID
INNER JOIN WorkRequest wr ON wr.ID = sreg.WorkRequestID
INNER JOIN SegmentRequirementEquipmentRequirement srer ON srer.SegmentRequirementID = wr.SegmentRequirementID
GROUP BY DATEADD(MINUTE, 30 * (DATE_PART(MINUTE, sreg.ScrapTime) / 30), DATEADD(HOUR, TIMESTAMPDIFF(HOUR, '0', sreg.ScrapTime), '0')),
sreg.EquipmentID,
sreas.Name
)
select temp.EquipmentID
from RAW_CPMS_AAR.equipment e, temp
Where e.ID = (select * from table(cfn_GetShiftIDFromDateTime_test(temp.DateTime::DATETIME, 0))) --this works with datetime
when i run this query above, i get Processing aborted due to error 300010:391167117; incident 3245754.. I believe this is an issue with the temp.datetime -- when i run the same codebut hardcoding the function input, i get the desired output.
with temp AS (
SELECT CAST(SUM(sreg.ScrapQuantity) AS INT) AS Quantity,
sreas.Name AS ScrapReason,
to_date((DATEADD(MINUTE, 30 * (DATE_PART(MINUTE, sreg.ScrapTime) / 30), DATEADD(HOUR, TIMESTAMPDIFF(HOUR, '0', sreg.ScrapTime), '0')))) AS DATETIME,
sreg.EquipmentID AS EquipmentID
FROM ScrapRegistration sreg
INNER JOIN ScrapReason sreas ON sreas.ID = sreg.ScrapReasonID
INNER JOIN WorkRequest wr ON wr.ID = sreg.WorkRequestID
INNER JOIN SegmentRequirementEquipmentRequirement srer ON srer.SegmentRequirementID = wr.SegmentRequirementID
GROUP BY DATEADD(MINUTE, 30 * (DATE_PART(MINUTE, sreg.ScrapTime) / 30), DATEADD(HOUR, TIMESTAMPDIFF(HOUR, '0', sreg.ScrapTime), '0')),
sreg.EquipmentID,
sreas.Name
)
select temp.EquipmentID
from RAW_CPMS_AAR.equipment e, temp
Where e.ID = (select * from table(cfn_GetShiftIDFromDateTime_test('2021-12-02 10:03:0.00'::datetime, 0))) --this works with datetime
it seems that that somwehere along the line, it's not liking the date format i put in. it's not returning me an error of not liking the input.
here is the function.
CREATE OR REPLACE FUNCTION DB_BI_DEV.RAW_CPMS_AAR.cfn_GetShiftIDFromDateTime (dateTime TIMESTAMP_NTZ(9), shiftCalendarID int)
RETURNS table (shiftID int)
AS
$$
WITH T0 (ShiftCalendarID, CurDay, PrvDay)
AS (
SELECT TOP 1
ID AS ShiftCalendarID,
DATEDIFF( day, BeginDate, dateTime ) % PeriodInDays + 1 AS CurDay,
( CurDay + PeriodInDays - 2 ) % PeriodInDays + 1 AS PrvDay
FROM RAW_CPMS_AAR.ShiftCalendar
WHERE ID = shiftCalendarID
OR ( shiftCalendarID IS NULL
AND Name = 'Factory'
AND BeginDate <= dateTime )
ORDER BY BeginDate DESC
),
T1 (TimeValue)
AS (
SELECT TIME_FROM_PARTS(
EXTRACT(HOUR FROM dateTime),
EXTRACT(MINUTE FROM dateTime),
EXTRACT(SECOND FROM dateTime))
)
SELECT ID as shiftID
FROM RAW_CPMS_AAR.Shift, T0, T1
WHERE Shift.ShiftCalendarID = T0.ShiftCalendarID
AND ( ( FromDay = T0.CurDay AND FromTimeOfDay <= T1.TimeValue AND TillTimeOfDay > T1.TimeValue )
OR ( FromDay = T0.CurDay AND FromTimeOfDay >= TillTimeOfDay AND FromTimeOfDay <= T1.TimeValue )
OR ( FromDay = T0.PrvDay AND FromTimeOfDay >= TillTimeOfDay AND TillTimeOfDay > T1.TimeValue )
)
$$
;

MySQL equivalent in MSSQL to assigning a variable and using it

I tried finding the answer, but maybe I am too new to MSSQL, I come from MySQL, so this is my question super simplified to go straight to the point:
Imagine we have a table "Things"
Thingie | Value
--------+-------
Thing1 | 10
Thing1 | 15
Thing1 | 16
In MySQL I could do something like this in a query:
SET #halfvalue := 0;
SELECT Thingie, Value,
(#halfvalue := Value / 2) AS HalfValue,
(#halfvalue / 2) AS HalfOfHalf
FROM Things
Which would return
Thingie | Value | HalfValue | HalfofHalf
--------+-------+-----------+------------
Thing1 | 10 | 5.00 | 2.50
Thing1 | 15 | 7.50 | 3.75
Thing1 | 16 | 8.00 | 4.00
Looks pretty simple, the actual one is a tad more complicated.
My problem is, in MSSQL I can't assign, and use a variable on the same SELECT. And I can't find anything similar to this functionality on this simple level.
Any solutions?
Edit, this is the select that contains all those nasty operations:
SELECT
fvh.DocEntry,
MAX( fvs.SeriesName ) AS "Serie",
MAX( fvh.DocNum - 1000000 ) AS "Número",
MAX( fvh.DocDate ) AS "Fecha",
MAX( fvh.U_FacNit ) AS "NIT",
MAX( fvh.U_FacNom ) AS "Nombre",
MAX( IIF( ISNULL( fvh.Address, '' ) = '', fvh.Address2, fvh.Address ) ) AS "Dirección",
SUM( fvd.GTotal - ISNULL( ncd.GTotal, 0 ) ) AS "Total",
IIF( MAX( fvh.CANCELED ) = 'Y' OR ( SUM( fvd.GTotal - ISNULL( ncd.GTotal, 0 ) ) = 0 ),
'Anulada',
IIF( SUM( fvd.GTotal ) > SUM( ISNULL( ncd.GTotal, 0 ) ) AND ( SUM( ISNULL( ncd.GTotal, 0 ) ) > 0 ),
'Devuelta',
'Emitida' )
) AS "Estado",
ROUND( ( ( SUM( fvd.GTotal - ISNULL( ncd.GTotal, 0 ) ) / 1.12 ) * 0.12 ), 4 ) AS "IVA",
ROUND( SUM( IIF( fvd.U_TipoA = 'BB',
( fvd.GTotal - ISNULL( ncd.GTotal, 0 ) ) - ( ( ( fvd.GTotal - ISNULL( ncd.GTotal, 0 ) ) / 1.12 ) * 0.12 ),
0 ) ), 4) AS "Bien",
ROUND( SUM( IIF( fvd.U_TipoA = 'S',
( fvd.GTotal - ISNULL( ncd.GTotal, 0 ) ) - ( ( ( fvd.GTotal - ISNULL( ncd.GTotal, 0 ) ) / 1.12 ) * 0.12 ),
0 ) ), 4) AS "Servicio",
ROUND( SUM( IIF( fvd.U_TipoA = 'N',
( fvd.GTotal - ISNULL( ncd.GTotal, 0 ) ) - ( ( ( fvd.GTotal - ISNULL( ncd.GTotal, 0 ) ) / 1.12 ) * 0.12 ),
0 ) ), 4) AS "No Aplica",
COUNT(fvd.LineNum) AS "Lineas", SUM(fvd.GTotal) AS "FCTotal",
SUM(ISNULL( ncd.GTotal, 0 )) AS "NCTotal"
/* Facturas */
FROM OINV AS fvh
LEFT JOIN NNM1 AS fvs ON fvs.Series = fvh.Series
LEFT JOIN INV1 as fvd ON fvd.DocEntry = fvh.DocEntry
/* Notas de Credito */
LEFT JOIN RIN1 AS ncd ON ncd.BaseEntry = fvh.DocEntry AND ncd.LineNum = fvd.LineNum
WHERE fvh.DocDate BETWEEN ? AND ? /*AND fvh.DocEntry = 1108*/
GROUP BY fvh.DocEntry
Thank you all for your time. I will dismantle my query and re-do it taking into consideration all of your input. Gracias, totales.
You think you can do this in MySQL:
SET #halfvalue := 0;
SELECT Thingie, Value,
(#halfvalue := Value / 2) AS HalfValue,
(#halfvalue / 2) AS HalfOfHalf
FROM Things;
But you are wrong. Why? MySQL -- as with every other database -- does not guarantee the order of evaluation of expression in a SELECT. The documentation even warns about this:
In the following statement, you might think that MySQL will evaluate #a first and then do an assignment second:
SELECT #a, #a:=#a+1, ...;
However, the order of evaluation for expressions involving user variables is undefined.
In both databases, you can use a subquery. In the most recent versions of MySQL (and just about any other database), you can also use a CTE:
SELECT Thingie, Value, HalfValue,
(HalfValue / 2) AS HalfOfHalf
FROM (SELECT t.*, (Value / 2) AS HalfValue
FROM Things t
) t;
The answer is simple: you can't do that in MSSQL, because when you try it you'll get:
Msg 141, Level 15, State 1, Line 3
A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.
which you most probably experienced.
The most simple workaround would be:
SELECT Thingie, Value, Value/2, Value/4 from Things
Other method:
select Thingie, Value, HalfValue, HalfValue / 2 from (
SELECT Thingie, Value, Value / 2 HalfValue from Things
) a
No, that doesn't work in SQL. The parameter value is not set until the query completes. You can do it in two steps:
DECLARE #halfvalue FLOAT = 0;
SELECT #halfvalue = ([Value] / 2)
FROM Things ;
SELECT Thingie
, [Value]
, HalfValue = [Value]/2
, HalfAgainValue = #halfvalue / 2
FROM Things ;

mysql average of best three

I have pieced this together from sites online and it works but not completely, what i need it to do is take the top 3 results and average them but it takes ALL results, can anyone point me in the right direction?
SELECT i.NAME,
e.comp,
Round(Avg(c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5
+ c.phase6), 2) AS "Average Score",
( CASE
WHEN compID = '7' THEN Concat(Round(Avg(
( (
c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5
+ c.phase6 ) / 400 ) * 100), 2), ' %')
WHEN compID = '5' THEN Concat(Round(Avg(
( (
c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5
+ c.phase6 ) / 600 ) * 100), 2), ' %')
WHEN compID = '3' THEN
Concat(Round(Avg(( ( c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5
+ c.phase6 ) / 600 ) * 100), 2), ' %')
ELSE 'Unspecified'
END ) AS "Average as Percent"
FROM jos_practicedetail c,
jos_comps e,
jos_practice g,
jos_members i
WHERE e.compsid = g.competition
AND g.practiceid = c.practicepid
AND i.memberid = c.competitorid
AND g.typeID = '2'
AND Year(g.pdate) = '2017'
AND (SELECT Count(*)
FROM jos_practicedetail b
WHERE b.competitorid = c.competitorid
AND b.practicepid = c.practicepid
AND ( b.phase1 + b.phase2 + b.phase3 + b.phase4 + b.phase5
+ b.phase6 ) >= (
c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5
+ c.phase6 )) <= 3
GROUP BY competitorid
HAVING Count(*) > 2
ORDER BY competitorid,
( Avg(c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5
+ c.phase6) ) DESC

Missing content of field CreatorFullName and ModifierFullName in GeneralJournalEntryLines

The business object GeneralJournalEntryLines contains the GL transaction lines of Exact Online. For performance tuning reasons, we are changing our scripts that copy data from Exact Online to our on-premise database to only include changes where possible instead of a full copy.
However, a query on GeneralJournalEntries joined with GeneralJournalEntryLines sometimes returns a null value in CreatorFullName and ModifiedFullName.
I've tried to reproduce new rows with this problem but those work fine.
Is this a database corruption? Or a join fault on my side?
The Exact Online query is:
use <DIVISION CODE>
select GE.Created GE_Created
,GE.Division GE_Division
,GE.EntryID GE_EntryID
,GE.EntryNumber GE_EntryNumber
,GE.FinancialPeriod GE_FinancialPeriod
,GE.FinancialYear GE_FinancialYear
,GE.JournalCode GE_JournalCode
,GE.Modified GE_Modified
,GE.Reversal GE_Reversal
,GE.Status GE_Status
,GE.Type GE_Type
,GL.AccountCode GL_AccountCode
,GL.AmountDC GL_AmountDC
,GL.AmountVATDC GL_AmountVATDC
,GL.AssetCode GL_AssetCode
,GL.CostCenter GL_CostCenter
,GL.CostUnit GL_CostUnit
,GL.CreatorFullName GL_CreatorFullName
,GL.Date GL_Date
,GL.Description GL_Description
,GL.GLAccountCode GL_GLAccountCode
,GL.LineNumber GL_LineNumber
,GL.ModifierFullName GL_ModifierFullName
,GL.OurRef GL_OurRef
,GL.ProjectCode GL_ProjectCode
,GL.Quantity GL_Quantity
,GL.VATBaseAmountDC GL_VATBaseAmountDC
,GL.VATCode GL_VATCode
,GL.VATPercentage GL_VATPercentage
,GL.VATType GL_VATType
from ExactOnlineREST..GeneralJournalEntries GE
inner join ExactOnlineREST..GeneralJournalEntryLines GL
on GE.EntryID=GL.EntryID
where GE.Status <> 50
or ( GE.Status = 50 and ( (GE.FinancialYear*100) + GE.FinancialPeriod = 201501 and GE.Modified > '09/01/2017 14:03:09' ) )
or ( GE.Status = 50 and ( (GE.FinancialYear*100) + GE.FinancialPeriod = 201502 and GE.Modified > '09/01/2017 14:03:09' ) )
or ( GE.Status = 50 and ( (GE.FinancialYear*100) + GE.FinancialPeriod = 201503 and GE.Modified > '09/01/2017 14:03:09' ) )
or ( GE.Status = 50 and ( (GE.FinancialYear*100) + GE.FinancialPeriod = 201504 and GE.Modified > '09/01/2017 14:03:09' ) )
or ( GE.Status = 50 and ( (GE.FinancialYear*100) + GE.FinancialPeriod = 201505 and GE.Modified > '09/01/2017 14:03:08' ) )
or ( GE.Status = 50 and ( (GE.FinancialYear*100) + GE.FinancialPeriod = 201506 and GE.Modified > '09/01/2017 14:03:08' ) )
or ( GE.Status = 50 and ( (GE.FinancialYear*100) + GE.FinancialPeriod = 201507 and GE.Modified > '09/01/2017 14:27:27' ) )
or ( GE.Status = 50 and ( (GE.FinancialYear*100) + GE.FinancialPeriod = 201508 and GE.Modified > '09/01/2017 14:27:27' ) )
or ( GE.Status = 50 and ( (GE.FinancialYear*100) + GE.FinancialPeriod = 201509 and GE.Modified > '09/01/2017 14:27:27' ) )
or ( GE.Status = 50 and ( (GE.FinancialYear*100) + GE.FinancialPeriod = 201510 and GE.Modified > '09/01/2017 14:27:26' ) )
or ( GE.Status = 50 and ( (GE.FinancialYear*100) + GE.FinancialPeriod = 201511 and GE.Modified > '09/01/2017 14:27:27' ) )
or ( GE.Status = 50 and ( (GE.FinancialYear*100) + GE.FinancialPeriod = 201512 and GE.Modified > '09/01/2017 14:27:26' ) )
local export results as "D:\Invantive\data\uit_EOL\40570GeneralJournals.csv" format csv
local exit
When using the query:
select *
from ExactOnlineREST..GeneralJournalEntryLines GL
where gl.modifierfullname is null or gl.creatorfullname is null
it seems that all rows where the modifiedfullname or creatorfullname is missing have an associated user GUID from a short list. It are also (based on creation date) all records which are of considerable age.
It seems that Exact Online APIs internally make a left outer join with the users table, for which no longer active users return no information.

mysql matching multiple and's and or's

I am trying to get rows from a table where there are matches on multiple other tables.
This is the query I am running.
SELECT qt.*, DATEDIFF(CURRENT_DATE, STR_TO_DATE(up.DOB, '%m-%d-%Y')) / 365 AS Age
FROM UserProfile AS up, Game AS g, QuestionTable AS qt
WHERE NOT EXISTS(SELECT * FROM Options WHERE UserID = 75 AND QID = qt.QID AND DateTime >= CURDATE())
AND g.Active = 1 AND g.QID = qt.QID
AND (((g.Gender = up.Gender OR g.Gender = 'B') AND ((g.City = up.City AND g.Zip = up.Zip AND g.Country = up.Country) OR g.Home = 0) AND ((Age BETWEEN g.Maximum AND g.Minimum) OR g.Age = 0) AND ((SQRT( POW( 69.1 * ( g.Latitude - -93.5746359 ) , 2 ) + POW( 69.1 * ( 44.9737707 - g.Longitude ) * COS( g.Latitude / 57.3 ) , 2 ) ) > g.Distance) OR g.Geo = 0)) OR g.Special = 0)
GROUP BY qt.QID
I have ran this expression through C# and it returns true, yet it is only matching on the 'g.Special = 0' part through MySql.
Any help on this would be much appreciated!
Resolved the issue by fixing some mistakes I made and changed the query to this,
SELECT *
FROM QuestionTable AS qt
WHERE NOT EXISTS
(SELECT * FROM Options WHERE UserID = 75 AND QID = qt.QID AND DateTime >= CURDATE())
AND EXISTS(SELECT g.* FROM UserProfile AS up, Game AS g WHERE g.Active = 1 AND g.QID = qt.QID AND(g.Special = 0 OR(
(g.Gender = up.Gender OR g.Gender = 'B') AND
((g.City = up.City AND g.zip = up.Zip AND g.Country = up.Country) OR g.Home = 0) AND
((SQRT( POW( 69.1 * ( g.Latitude - 44.9737707 ) , 2 ) + POW( 69.1 * ( -93.5746359 - g.Longitude ) * COS( g.Latitude / 57.3 ) , 2 ) ) < g.Distance) OR g.Geo = 0) AND
((DATEDIFF(CURRENT_DATE, STR_TO_DATE(DOB, '%m/%d/%Y'))/365.25 BETWEEN g.Minimum AND g.Maximum) OR g.Age = 0))))