MSReport is showing 1 day behind for expiry date, compared to CRM? - 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

Related

Port MySQL script to MS SQL -> simultaneous data asignement and retrieval

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

Convert time "28:45" to "4:45" MySQL

I'm looking for a way to order my results based on the actual time. In my table yo can see values like:
1,23:45
2,9:45
3,27:43
When I do a query I would like to know how to order them based on their actual 24 hour time.
Ex:
3,3:43
2,9:45
1,23:45
Notice how it changes 27:43 to 3:43, and creates the order.
Where I am using it, in this query:
SELECT *,COALESCE(ADDTIME(s.`departure_time`,SEC_TO_TIME(rt.delay)),s.`departure_time`) as `rt_time` FROM `stop_times` s INNER JOIN `trips` t ON s.`trip_id` = t.`trip_id` INNER JOIN `stops` st ON st.`stop_id` = s.`stop_id` INNER JOIN `routes` r ON r.`route_id` = t.`route_id` LEFT JOIN `rt_trips` rt ON t.`trip_id` = rt.`trip_id` where (s.`stop_id` = 'CB900') and ( ( s.`departure_time` >= '00:50' and s.`departure_time` <= '05:50') OR ( s.`departure_time` >= '24:50' and s.`departure_time` <= '29:50') ) and (s.`pickup_type` = '0') and (t.`service_id` IN ('removed to make it easier')) HAVING (`rt_time` BETWEEN '01:50' and '05:50' ) ) OR ( `rt_time` BETWEEN '25:50' and '29:50' ) ORDER BY `order` ASC
Explanation:
Information is a transit schedule, that may go forward onto the next day which may be a saturday. So, times may become 25:50, where that means 1:50 the next day.
Thanks
Cyrus
Hmmm, if you just want to get a value between 0 and 24 hours, then I would do:
select concat(mod(substring_index(time_column, ':', 1) + 0, 24), ':',
substring_index(time_column, ':', -1)
)
Try this function on the time_column
concat(mod(substr(time_column,1,INSTR(time_column, ':')-1),24)
,substr(time_column,INSTR(time_column, ':'),3)
)
You might need to cast date to string to integer, do the maths, and again cast it to time. But the fiddle version seems to work properly on varchar to integer conversion. Check this
http://sqlfiddle.com/#!9/ff60f9/1

Slow mySql update containing Join

I have a system that collects data from production reports (CSV files) and puts them into a mySql DB.
I have an header table, that contain the production data of sequential report with same setting, and a table with the single reports, connected to the first one (trfCamRep.hdrId -> trfCamHdr.id).
I have a query to calculate the total report, the dubt and the faulty, and the maxTs. These datas are used in the visualizator.
The query is too slow, it requires 9sec.
Can you help me to speed up it?
SET #maxId:=(SELECT MAX(id) FROM trfCamHdr WHERE srcCod='7');
UPDATE trfCamHdr AS hdr
LEFT JOIN (SELECT hdrF.id,COUNT(*) AS nTot,
SUM(IF(res=1,1,0)) AS nWrn,SUM(IF(res=2,1,0)) AS nKO,
MAX(ts) AS maxTS
FROM trfCamHdr AS hdrF
JOIN trfCamRep AS repF ON repF.hdrId=hdrF.id
WHERE clcEnd=0 AND srcCod='7'
GROUP BY hdrF.id) AS valT ON valT.id=hdr.id
SET hdr.clcEnd=IF(hdr.id<#maxId,1,0),
hdr.nTot=valT.nTot,
hdr.nWrn=valT.nWrn,
hdr.nKO=valT.nKO,
hdr.maxTS=valT.maxTS
WHERE hdr.id>=0 AND hdr.clcEnd=0 AND hdr.srcCod='7';
Note trfCamHdr has these columns:
id (primary key)
clcEnd : flag of end calculation (the last remain to 0 because in progress)
nTot : elements with this header
nWrn : elements with res = 1
nKO : elements with res = 2
maxTs : TS of the last element
trfCamRep has these columns:
hdrId (refer to id of trfCamHdr)
res : 0 good, 1 dubt, 2 fault
ts : report timestamp
I'd take this out:
SET #maxId:=(SELECT MAX(id) FROM trfCamHdr WHERE srcCod='7');
And any allusions to the MaxId variable, I believe it to be redundant.
Everything you do will be lower than the max id, and it will take time to calculate if its a big table. You are already checking for srcCod = 7, so it isn't necessary.
In fact, it would miss the update on the one with the actual max id, which is not what I believe you want.
Your left join will also update all other rows in the table with NULL, is that what you want? You could switch that to an inner join, and if your rows are already null, they will just get left alone, rather than getting updated with NULL again.
Then you could just switch out this:
SET
hdr.clcEnd = IF(hdr.id < #maxId, 1, 0),
To
SET
hdr.clcEnd = 1,
Here is the rewritten thing, as always, back your data up before trying:
UPDATE trfCamHdr AS hdr
INNER JOIN
(SELECT
hdrF.id,
COUNT(*) AS nTot,
SUM(IF(res = 1, 1, 0)) AS nWrn,
SUM(IF(res = 2, 1, 0)) AS nKO,
MAX(ts) AS maxTS
FROM
trfCamHdr AS hdrF
JOIN trfCamRep AS repF ON repF.hdrId = hdrF.id
WHERE
clcEnd = 0 AND srcCod = '7'
GROUP BY hdrF.id) AS valT ON valT.id = hdr.id
SET
hdr.clcEnd = 1,
hdr.nTot = valT.nTot,
hdr.nWrn = valT.nWrn,
hdr.nKO = valT.nKO,
hdr.maxTS = valT.maxTS
WHERE
hdr.id >= 0 AND hdr.clcEnd = 0
AND hdr.srcCod = '7';
I found the solution: I created a KEY on hdrId column and now the query requires 0.062s.

Group by changing boolean value

Hi i have the following SQL question:
SELECT station_id, filling_station_status,date_created ,
case when filling_station_status="FREE" then 0
else 1 end as status
FROM efahrung.electric_station_time_status
where station_id=11
In my table have a column filling_station_status.
It can be "FREE" or "IN_USE".
I want to group elements so, that if the filling_station_status is changed (from "FREE" to "IN_USE") it will create a date range in my case, date_created.
In the next change again from ("IN_USE" to "FREE") it creates a new date range.
Thanks for a suggestions.
If you just need SQL query to generate date range in output, then try this:
Select s.station_id,
Coalesce(e.filling_station_status, s.filling_station_status) fillingStationStatus,
case e.filling_station_status
when "FREE" then 0 else 1 end status,
s.date_created startDate,
e.date_created endDate
From efahrung.electric_station_time_status s
Left Join efahrung.electric_station_time_status e
On e.station_id = s.station_id
and s.filling_station_status = 'IN_USE'
and e.filling_station_status = 'FREE'
and e.date_created =
(Select Min(date_created)
From efahrung.electric_station_time_status
Where station_id = s.station_id
and date_created > s.date_created)

Trying to merge multiple UPDATE statements into one within SQL stored procedure

I have multiple update statements in a stored procedure (as shown below).
Question is I am trying to combine them into one UPDATE statement as there is a performance issue (takes longer to execute stored procedure). I tried putting columns (such as PONUMBER, VENDORID etc) in a single update statement but it is throwing errors.
Please suggest.
UPDATE rptMaster SET PONUMBER = (select top 1 poMaster.PONUMBER from poMaster where poMaster.ITEMNMBR =rptMaster.ITEMNMBR and
poMaster.UnCommited > 0)
UPDATE rptMaster SET VENDORID = (select top 1 poMaster.VENDORID from poMaster where poMaster.ITEMNMBR =rptMaster.ITEMNMBR and
poMaster.UnCommited > 0)
UPDATE rptMaster SET DUEDATE = (select top 1 poMaster.REQDATE from poMaster where poMaster.ITEMNMBR =rptMaster.ITEMNMBR and
poMaster.UnCommited > 0)
UPDATE rptMaster SET POQTYORDER = (select top 1 (poMaster.QTYORDER / rptMaster.UOMQTY) from poMaster where poMaster.ITEMNMBR =rptMaster.ITEMNMBR and
poMaster.UnCommited > 0)
Mine is similar to polkduran's:
WITH PO AS (
SELECT PONUMBER
, VENDORID
, REQDATE
, QTYORDER
, ITEMNMBR
, ROW_NUMBER() OVER (PARTITION BY ITEMNMBR ORDER BY ??) as RN
FROM poMaster
WHERE UnCommited > 0
)
UPDATE rptMaster
SET PONUMBER = po.PONUMBER
, VENDORID = po.VENDORID
, DUEDATE = po.REQDATE
, POQTYORDER = po.QTYORDER / rptMaster.UOMQTY
FROM rptMaster
JOIN PO
ON PO.ITEMNMBR = rptMaster.ITEMNMBR
and PO.RN = 1
I'm using a Common Table Expression (CTE) to assign a row number to each poMaster record, with the records for each value of ITEMNMBR numbered separately. This allows us to pick to the first record for each ITEMNBR in our JOIN, later, similar to the way you were using Top 1 in your subqueries.
Please note, though: because you didn't indicate how you wanted to select the Top 1 record in your query, I had to leave the ORDER BY clause in the CTE unspecified. (I put ?? in as a placeholder.) You need to specify one or more sort fields in place of the ?? so it knows how to sort and number the records.
You can make an update using a join clause:
update rpt
set
PONUMBER = po.PONUMBER,
VENDORID = po.VENDORID,
DUEDATE = po.REQDATE,
POQTYORDER = (po.QTYORDER / rpt.UOMQTY)
from rptMaster rpt
inner join poMaster po
on po.ITEMNMBR = rpt.ITEMNMBR
where po.UnCommited > 0
I don't have a way to test it right now but that might work.