I write a query the result of the query is fine but issue with the time that is taking to complete the execution. For increase the performance i create index as per my query so this decrease from 5 minutes to 0.44 seconds. But i want to make this more faster. The issue i release with my function that i comment then its execution time is 0.00 but the function i am using is important for me. Is any option to decrease my execution time of my query .
**My function*
ALTER FUNCTION [dbo].[fnCount]
(
#StartDate DATE,#EndDate DATE,#DropDate DATE
)
RETURNS INT
AS
BEGIN
DECLARE #WeekStartDate DATE
DECLARE #WeekEndDate DATE
DECLARE #Count AS INT
SET #Count=0
SET #WeekStartDate=CONVERT(DATE,DATEADD(dd, -(DATEPART(dw, #DropDate)-1), #DropDate))
SET #WeekEndDate=CONVERT(DATE,DATEADD(dd, 7-(DATEPART(dw, #DropDate)), #DropDate))
IF #StartDate <= #WeekStartDate
SET #StartDate=#WeekStartDate
IF #EndDate >=#WeekEndDate
SET #EndDate=#WeekEndDate
SELECT #Count=COUNT(distinct DROPDATE)
FROM orde_
WHERE orde_.CANCELLED = 0
AND DROPDATE >= #StartDate AND DROPDATE <= #EndDate
AND (DISPID IS NULL OR DISPID NOT IN ( '291', '327') )
RETURN #Count
END
Query
SELECT READYDATE,TOTAL,DRV1PAY,ORDERNUM,
CASE WHEN dbo.fnCount('20170901','20171031',DROPDATE) >=4
THEN (CONVERT(VARCHAR(4),LEFT(DROPDATE,4)) + '' + CONVERT(VARCHAR(4),DATEPART( wk, DROPDATE)))
ELSE NULL
END AS WEEKOfYear1,
FROM orde_
WHERE CANCELLED = 0 AND DROPDATE >='20170901' AND DROPDATE <='20171031'
AND (DISPID IS NULL OR DISPID NOT IN ( '291', '327') )
ORDER BY DISPID
Thanks for your help and comments
Related
I have a query :
insert into fookoo_business
select stat_date, sum(spend), sum(revenue)
from hooloo_business;
that i want to run for each date from '2017-01-20' until yesterday (it means the query will run 434 times if we're at 01/04/2018), for each date separately
(in a loop).
how can i create a loop in Mysql to do it for me?
I have tried:
creating procedure for the query select #stat_date, sum(spend), sum(revenue)
I called 'query'
then :
CREATE PROCEDURE loop_procedure()
BEGIN
SET #stat_date='2018-03-20';
CALL 'query';
REPEAT
SET #stat_date = #stat_date + INTERVAL 1 DAY;
UNTIL #stat_date = CURDATE() END REPEAT;
END
eventually i've used the following logic within a stored procedure to fetch the data:
PROCEDURE `x_monitoring_loop`()
BEGIN
DECLARE i INT;
DECLARE len INT;
SET len = 434;
SET i = 0;
WHILE (i < len) DO
SET #stat_date= CURDATE()-INTERVAL 1 DAY;
SET #stat_date= #stat_date- INTERVAL i DAY;
Insert query;
SET i = i +1;
END WHILE;
This way the query ran 434 times for each day, beginning at current date - 1 day.
I do not know why you want to use a procedure,I think we can just use a query sql to do it:
INSERT INTO fookoo_business
SELECT stat_date, SUM(spend), SUM(revenue)
FROM hooloo_business
WHERE stat_date BETWEEN STR_TO_DATE('2017-01-02', '%Y-%m-%d') -- start date
AND DATE_SUB(NOW(), INTERVAL 1 DAY) -- end date
GROUP BY stat_date;
I would like to change the interval in this SQL statement, based on a parameter in a stored procedure. I want to use three different intervals: 1 day, 8 hours, 1 hour
CREATE DEFINER= 'dbshizzle' PROCEDURE `getData`(in sD text(17), in sT text(8))
BEGIN
select stime, sval
from tblNumber
where sDix = 'allright'
and timestamp >= now() - interval 1 day
order by timestamp;
END
Should I use an IF statement with an integer parameter, or a text parameter?
How about just adjusting the parameter and passing in the value as hours?
CREATE DEFINER = 'dbshizzle' PROCEDURE `getData`(
in in_sD text(17), -- should change to varchar
in in_sT text(8), -- should change to varchar
in in_hours int
)
BEGIN
select stime, sval
from tblNumber
where sDix = 'allright'
and timestamp >= now() - interval in_hours hour
order by timestamp;
END;
I am very new to mysql scripts , I want to execute this query by incrementing 00:00:00 time to 30 minutes .
something like this
Select count(*)
FROM ctrdb.CTR_LINE_ITEM
where LOAD_DATE BETWEEN '2016-05-18 00:00:00' AND '2016-05-18 00:30:00'
order by load_date;
Select count(*)
FROM ctrdb.CTR_LINE_ITEM
where LOAD_DATE BETWEEN '2016-05-18 00:30:00' AND '2016-05-18 00:60:00'
order by load_date;
Can you guys please help me ?
if you wan to achieve this in mysql and want to get separate resultset for each query
then you need to run your query in loop by using stored procedure.
read loop in mysql http://www.mysqltutorial.org/stored-procedures-loop.aspx
or there are not multiple queries then you can use union as well
DELIMITER $$
CREATE PROCEDURE getdata()
BEGIN
DECLARE x INT;
DECLARE maximum INT; # you can use date as well
DECLARE startdate DATE;
DECLARE enddate DATE;
SET x =0;
SET maximum = 10;
SET startdate = '2016-05-18 00:00:00';
loop_label: LOOP
IF x > 10 THEN
LEAVE loop_label;
END IF;
SET x = x + 1;
SET enddate = startdate + INTERVAL 30 MINUTE;
Select count(*) ,startdate
FROM ctrdb.CTR_LINE_ITEM
where LOAD_DATE BETWEEN '2016-05-18 00:00:00' AND '2016-05-18 00:30:00'
order by load_date;
SET startdate = startdate + INTERVAL 30 MINUTE;
END LOOP;
END $$
DELIMITER ;
In SQL Server 2008 I have a startdate and an enddate being passed to my procedure. I need to check each date in the range to see if it exists in my validworkday table. I have no clue where to begin on this, but this is how start/end day are set-up
Declare #startdate date, #enddate date
Set #startdate = '01/01/2015'
Set #enddate = '04/16/2015'
Now how can I iterate each date in this span to see if validworkday = true for it? The check I would need to run is like so (checking each date)
Select isvalidworkday
from validworkdays
where date = '01/01/2015'
Select isvalidworkday
from validworkdays
where date = '01/02/2015'
This is syntax that I found from #Incidently years ago (I don't remember where that original post is, but hopefully this will be enough to give the credit), that I still use today. All I did was slightly tweak his syntax to insert the data into a temp table and add a cursor to iterate each individual date.
DECLARE #DateFrom smalldatetime, #DateTo smalldatetime, #firstdate date;
SET #DateFrom='20000101';
SET #DateTo='20081231';
-------------------------------
WITH T(date)
AS
(
SELECT #DateFrom
UNION ALL
SELECT DateAdd(day,1,T.date)
FROM T
WHERE T.date < #DateTo
)
SELECT date
INTO #AllDates
FROM T OPTION (MAXRECURSION 32767);
Declare c1 Cursor For
Select date
FROM #AllDates
Open c1
Fetch Next From c1 Into #firstdate
While ##FETCH_STATUS = 0
Begin
--Do whatever processing you need here
Fetch Next From c1 Into #firstdate
End
Close c1
Deallocate c1
Code should only live in one place and not be rewritten. Create functions (once) like GetAllIntsBetween(), GetAllMonths(), GetAllDates(), etc. Then used them like:
DECLARE #startdate date = '01/01/2015', #enddate date = '04/16/2015'
SELECT allDates.TheDate,
isnull(v.isvalidworkday, false) AS isvalidworkday
FROM dbo.GetAllDates(#startdate, #enddate) AS allDates
LEFT JOIN validworkdays AS v
ON allDates.TheDate = v.MyDate
The GetAllDates() would be:
CREATE FUNCTION dbo.GetAllDates(#Start DATETIME, #End DATETIME)
RETURNS
#AllDates TABLE
(
TheDate DATETIME
)
AS
BEGIN
IF #Start > #End
BEGIN
DECLARE #Temp DATETIME
SET #Temp = #Start
SET #Start = #End
SET #End = #Temp
END
WHILE #Start <= #End
BEGIN
INSERT INTO #AllDates
VALUES(#Start)
SET #Start = DATEADD(DAY, 1, #Start)
END
RETURN
END
(note: can change DATETIME to DATE)
I'd like to write a query or stored procedure to retrieve less and less records over time from a relational database.
Think of this like populating the Google Finance stock chart: The past few days will have all ticks fit the day, and the further you go back, less and less ticks are displayed on each date. All ticks will show for today, 50% of ticks will show for one week ago, 30% for one month ago, and 10% for one year ago. Think of this like a gradient.
Is it possible to achieve this with one query? Or perhaps it would be necessary to use multiple queries? What might this look like?
Note that record ids are non-contiguous (there are gaps), but each record has a timestamp for determining order.
Also note that I am using MySQL.
Here is the structure of my table:
quotes
id
security_id
last_price
bid_price
ask_price
date
timestamp
trade_volume
cumulative_volume
average_volume
created_at
Sounds like you are looking for a constant set of records that represent the time-span. You can do so by defining a control date set.
Here's a sample query (doesn't account for weekends and holidays but that can be added):
POPULATE:
CREATE TABLE #quotes
(
id int identity(1,1)
,security_id VARCHAR(50)
,last_price FLOAT
,bid_price FLOAT
,ask_price FLOAT
,[date] DATETIME
,[timestamp] DATETIME
,trade_volume FLOAT
,cumulative_volume FLOAT
,average_volume FLOAT
,created_at DATETIME
)
DECLARE #i int
set #i = 100000
WHILE #i > 0
BEGIN
INSERT INTO #quotes (
security_id
,last_price
,bid_price
,ask_price
,[date]
,[timestamp]
,trade_volume
,cumulative_volume
,average_volume
,created_at
)
values( 'IBM US'
, 100.00 + RAND()
, 100.00 + RAND()
, 100.00 + RAND()
, DATEADD(MINUTE, -1* #i, GETDATE())
, DATEADD(MINUTE, -1* #i, GETDATE())
, 10000000.00 + RAND()*1000000.00
, 10000000.00 + RAND()*1000000.00
, 10000000.00 + RAND()*1000000.00
,getdate())
set #i= #i-1
END
You can change around the time span, but the following will give you around 1000 records that represent the set from start to finish.
DECLARE #StartDate DATETIME,
#EndDate DATETIME,
#j FLOAT,
#step FLOAT
set #StartDate = GETDATE()-20
SET #EndDAte = GETDATE()
set #j = 0.0
CREATE TABLE #TimeTable
(
IntervalDate DATETIME
)
--say you always want 1000 measures
--use the datediff value to define the step size:
select #step = DATEDIFF(MINUTE, #StartDate, #EndDate)/1000.0
WHILE #j < DATEDIFF(MINUTE, #StartDate, #EndDate)
BEGIN
INSERT #TimeTable (IntervalDate) VALUES (DATEADD(minute, #j, #StartDate))
SET #j = #j+#step
print #j
END
select security_id
,last_price
,bid_price
,ask_price
,[date]
,[timestamp]
,trade_volume
,cumulative_volume
,average_volume
,created_at
from #Quotes q
join #TimeTable t on dateadd(mi, datediff(mi, 0, q.date), 0) = dateadd(mi, datediff(mi, 0, t.IntervalDate), 0)