I have been trying to make this work for hours but I can't really find a way to do it. I have a MySQL script that I need to migrate to MS SQL 2014, however, I can't seem to make it work. As far as I have understood, the big issue is that MySQL allows this kind of instructions:
SELECT #row_number = #row_number + 1, hora_int FROM table1;
where you assign a value at the same time you retrieve data, but MS SQL does not.
I have a relatively big script which has that issue:
SELECT GLOBAL.year, GLOBAL.month, '1111111' as metric_id, GLOBAL.margin as metric_value FROM (SELECT A.year,
A.month,
CASE
WHEN A.month = 1 THEN (#csum_fdo := A.imp)
ELSE (#csum_fdo := #csum_fdo + A.imp) END as margin
FROM (SELECT Act.year, Act.month, Act.imp - Pas.imp as imp
FROM (SELECT year(tie.date) as year, month(tie.date) as month, sum(importe) as imp
FROM accounting con,
dim_time tie,
dim_account cta
WHERE con.account_date = tie.date
AND con.account = cta.nivel_10
AND cta.level_id = '2'
AND con.subtype_id <> 'O'
GROUP BY year(tie.date),
month(tie.date)) Act,
(SELECT year(tie.date) as year, month(tie.date) as month, sum(importe) * -1 as imp
FROM accounting con,
dim_time tie,
dim_account cta
WHERE con.account_date = tie.date
AND con.account = cta.nivel_10
AND cta.level_id = '3'
AND con.subtype_id <> 'O'
GROUP BY year(tie.date),
month(tie.date)) Pas
WHERE Act.year = Pas.year
AND Act.month = Pas.month) A,
(SELECT #csum_fdo := 0) E) GLOBAL
Can anybody point me in the direction of what I have to do to recreate the code in MS SQL? Thank you all in advance
In SQL Server and (MyQL 8+), you use window functions. The equivalent of:
SELECT #row_number = #row_number + 1, hora_int
FROM table1
ORDER BY col;
is:
SELECT ROW_NUMBER() OVER (ORDER BY col), hora_int
FROM table1;
If you provide sample data and desired results, it is much easier to figure out what functions you really need.
My big problem lied in this line:
CASE
WHEN A.month = 1 THEN (#csum_fdo := A.imp)
ELSE (#csum_fdo := #csum_fdo + A.imp) END as margin
but as Gordon Linoff pointed me. this problem could be solved with window functions, the right translation od that function is:
SUM(A.imp) OVER(PARTITION BY A.Year ORDER BY A.month) as margin
it ended up being easier than I thought
Thanks a lot and I hope it can help others as well
Related
Pls help to tune this query
select
substr(Extend(current,year to second)- extend(outr.eventDateTime,year to second)+INTERVAL(300) MINUTE(3) TO MINUTE,-8) as duration,
else 'Hold' end as state
from
A as outr,
B as rs
where
eventDateTime = (select max(eventDateTime) from A as innr where outr.aID=innr.aID and outr.pID=innr.pID)
and eventDateTime >= Date(current)
and rs.rID = outr.aID
and rs.pID = outr.pID
order by rName
For starters, add this index:
INDEX(aid, pid)
This smells like a "groupwise max". See the tag I added.
I have a strange problem which is when I run the sql command first time it shows wrong result, but when I run the same code for second time the result is correct.
The wrong result is:
The expected result is:
the sql command is:
SELECT srNumber, end_on, start_on, teamEntityId
FROM (
SELECT srNumber, end_on, start_on, teamEntityId,
#lastrow := IF(#sr_Number = srNumber, #lastrow + 1,
IF(#sr_Number := srNumber, 1, 0)) AS lastrow
FROM assign
CROSS JOIN (SELECT #lastrow := 0, #sr_Number = '') AS vars
ORDER By srNumber, assignId DESC) AS t
WHERE t.lastrow = 1 AND t.teamEntityId = '00000168752ac161-02420aff00230001'
In more recent versions of MySQL, you need to order the data before using variables. So replace:
FROM assign
with:
FROM (SELECT a.* FROM assign a ORDER BY srNumber, assignId DESC) a
I would like to thank Alex and Salman A who solved the problem which is:
replace the below code
#sr_Number = ''
to
#sr_Number := ''
I have a complicated SQL query running on a MSSQL server. I need to change it to make it work also on a MySQL database, however I do not know how to do this. The query is the following and is used to build a complicated Sankey graph in a BI tool
SELECT Id, Delivery_Date, Queue, Step1, Step2, Step3, Step4, Step5, Step6, Step7,
CONVERT(DECIMAL(16,16),RAND((CHECKSUM(NEWID())))*(1 - 0.999999999)+0.999999999) as Counter
FROM
(SELECT t.ID as Id, t.DELIVERY_DATE as Delivery_Date, t.QUEUE as Queue, CONCAT(t.EVENT_NAME,' ', t.EVENT_STATUS, ' ',t .ENDING) as edsda,
'Step' + cast(row_number() over (partition by ID order by ID)
as varchar(10)) ColumnSeq
FROM (SELECT DISTINCT e.[ID] AS ID,
e.[DIALOG_DELIVERY_DATE] AS DELIVERY_DATE,
e.[QUEUE_ID] as QUEUE,
s2.[STEP_NUMBER] AS STEP_NUMBER,
s2.[CURRENT_EVENT] AS EVENT_NAME,
s2.[EVENT_STATUS] as EVENT_STATUS,
e.[DELIVERY_END] AS DELIVERY_END,
CASE WHEN s2.[STEP_NUMBER] = max(s2.[STEP_NUMBER]) over (partition by s2.[ID])
and s2.[EVENT_NUMBER] = min(s2.[EVENT_NUMBER]) over (partition by s2.[ID], s2.[STEP_NUMBER]) THEN e.[DELIVERY_END] ELSE NULL END as ENDING
FROM [dbo].[DELIVERY_STEP_EVENTS] s1,
[dbo].[DELIVERY_STEP_EVENTS] s2,
[dbo].[DELIVERY_EVENTS] e
WHERE s1.[ID] = s2.[ID]
AND e.[ID] = s2.[ID]
AND s1.[EVENT_NAME] = s2.[EVENT_NAME]
AND s1.[STEP_NUMBER] <= s2.[STEP_NUMBER] AS t) AS temp
pivot
(max(edsda)
for ColumnSeq in (Step1,Step2,Step3,Step4, Step5, Step6, Step7)
)
AS Piv
My biggest issue so far has been the RAND((CHECKSUM(NEWID()))) which I do not know how to change to MySQL.
Any help would be greatly appreciated.
My biggest issue so far has been the RAND((CHECKSUM(NEWID()))) which I
do not know how to change to MySQL.
RAND((CHECKSUM(NEWID()))) should behave identical to RAND() function in MySQL. So you could simply replace this:
CONVERT(DECIMAL(16,16),RAND((CHECKSUM(NEWID())))*(1 - 0.999999999)+0.999999999)
With this:
CAST(RAND() * (1 - 0.999999999) + 0.999999999 AS DECIMAL(16, 16))
SQL Server
MySQL
Currently when I look at the expiry date section for insurance on my MSReport Builder it is 03/04/2017, but the expiry date section for my insurance in CRM is 04/04/2017 which is the correct and right, however in the report it is 1 day behind, therefore I was wondering why and what might be the fix to this? because I want it to show the same as CRM 04/04/2017, I've been researching and some articles said use UTC THE ONE THAT DONT START WITH 23 hours, not entirely sure how to put this in my query, I’m in the UK, and CRM options are for already set for UK as I checked it already. Again, please advise fix to this?
SELECT 'PAS ' +
SectionName AS SectionName,
SectionKey,
FormName,
ItemName,
ImportSequenceNumber,
ExpiryDate,
ExpiresOn,
#Param_MonthlyStatement_EntityRecordId AS AccountId
FROM
(SELECT
sect.mm_name AS SectionName,
sect.mm_key AS SectionKey,
frm.mm_name AS FormName,
frm.mm_name AS ItemName,
frm.mm_importsequencenumber AS ImportSequenceNumber,
MAX(frmans.mm_expires) AS ExpiryDate,
DATEADD(m, 2, GETDATE()) AS ExpiresOn
FROM Filteredmm_section AS sect INNER JOIN
mm_form AS frm ON sect.mm_sectionid = frm.mm_section INNER JOIN
mm_formanswer AS frmans ON frmans.mm_form = frm.mm_formId INNER JOIN
Account AS acc ON frmans.mm_AccountID = acc.AccountId
WHERE (sect.mm_name LIKE '%-%')
AND (sect.mm_parentsection IS NULL)
AND (CONVERT(NVARCHAR(250), frmans.mm_AccountID)
= #Param_MonthlyStatement_EntityRecordId)
AND ( acc.mm_supplier = 1)
GROUP BY sect.mm_name, sect.mm_key, frm.mm_name, frm.mm_importsequencenumber
HAVING (MAX(frmans.mm_expires) BETWEEN GETDATE() AND DATEADD(m, 2, GETDATE()))) AS t1
WHERE (NOT EXISTS (SELECT TOP (1) mm_accountid FROM Filteredmm_formanswer
WHERE (mm_formname = t1.FormName) AND (mm_accountid = #Param_MonthlyStatement_EntityRecordId) AND (mm_statusname = 'Awaiting Verification')))
ORDER BY SectionName, FormName, ImportSequenceNumber
You might want to get the expiry date from the filtered table, because I can see there is a filtering used, perhaps try
INNER JOIN Filteredmm_formanswer AS frmans ON frmans.mm_form = frm.mm_formId
I have a mysql query where I need to calculate values like ROUND(SUM(temp.total_pq),2) multiple times, so I defined variables to avoid repeating them.
But the line 5 in the query returns wrong value in the results. The value for #diff_client_partner_qtty := ROUND((#partner_qtty_all_runs - #client_qtty_all_runs), 2) AS diff_client_partner_qtty is always NULL the first time I run and thereafter always 84.
I asked the in-house DBA and he says I should not use variables in my query like this because the order in which mysql will set values for the variable is not predictable and hence I may get NULL value.
But why? Also can someone please propose then another way whereby I can avoid rewriting ROUND(SUM(temp.total_pq),2) multiple times other than a subquery. I would prefer to avoid a subquery because I think even in its current form query is not that readable.
SELECT temp.dtaccounted AS accounting_period,
#partner_qtty_all_runs := ROUND(SUM(temp.total_pq),2) AS partner_qtty_all_runs,
ROUND(temp.mmq,2) AS mopay_qtty,
#client_qtty_all_runs := ROUND(SUM(temp.total_cq),2) AS client_qtty_all_runs,
#diff_client_partner_qtty := ROUND((#partner_qtty_all_runs - #client_qtty_all_runs), 2) AS diff_client_partner_qtty,
#partner_gtv := ROUND(temp.total_pq_gtv, 2) AS partner_gtv,
#client_gtv := ROUND(temp.total_cq_gtv,2) AS client_gtv,
#diff_client_partner_gtv := ROUND((#partner_gtv - #client_gtv), 2) AS diff_client_partner_gtv,
temp.stariffcurrency AS tariffcurrency,
ROUND(#diff_client_partner_gtv * ffactor, 2) AS diff_client_partner_gtv_eur,
temp.scountry AS country,
temp.spartnererpid AS partner_erp_id,
c.name AS partner_name,
temp.nproducttype AS product,
temp.capping
FROM
(SELECT SUM(npartnerquantity) AS total_pq,
SUM(nmindmaticsquantity) AS mmq,
SUM(nclientquantity) AS total_cq,
SUM(dgrosstariff * npartnerquantity) AS total_pq_gtv,
SUM(dgrosstariff * nclientquantity) AS total_cq_gtv,
nrun,
vb.scountry,
vb.spartnererpid,
dtaccounted,
stariffcurrency,
vb.nproducttype,
cq.bisenabled AS capping
FROM report_table vb,
client_table cq
WHERE vb.accperiod > '2013-12-01'
AND vb.partnerid = cq.partnerid
AND vb.scountry = cq.scountry
AND vb.nproducttype = cq.nproducttype
AND (cq.dtvalidto IS NULL
OR cq.dtvalidto > vb.accperiod)
GROUP BY scountry,
nproducttype,
partnerid,
nrun,
accperiod
) temp,
customer c,
currency_conversion cc
WHERE temp.partnerid = c.erp_id
AND temp.total_pq <> temp.total_cq
AND cc.scurrencyfrom = temp.stariffcurrency
AND cc.scurrencyto = 'EUR'
AND cc.dtrefdate = temp.accperiod
GROUP BY temp.scountry,
temp.partnerid,
c.name,
temp.nproducttype,
temp.accperiod
ORDER BY temp.accperiod,
temp.scountry,
temp.partnerid,
temp.nproducttype,
temp.capping \G;