I have query which returns hourly data. But I want to get daily data from this query, so all the hourly data per day would be averaged to daily data.
declare #Days int
set #Days = -1
select
dateadd(hour,datepart(hour,Timestamp),cast(CAST((Timestamp) as date) as datetime)) as [Time]
,[value]
from [Employee]
where dateadd(hour,datepart(hour,Timestamp),cast(CAST((Timestamp) as date) as datetime)) >= CONVERT(date, DATEADD(DAY, #Days, GETDATE()))
Assuming you have additional columns you want to average and group by date, you can try something like:
DECLARE #Days int = -1;
SELECT
CAST(Timestamp AS date) AS date
, AVG(Value) AS Value
FROM [Employee]
WHERE Timestamp >= DATEADD(day, #Days, CAST(GETDATE() AS date))
GROUP BY CAST(Timestamp AS date)
ORDER BY date;
Note the refactored WHERE clause that avoids applying a function to the column value. This will allow an index on Timestamp to be used efficiently (sargable expression).
Related
I have tried many different queries that already given here, but it also shows previous year data, for example, if use this query
Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6, current_timestamp)), 0)
or
DATEADD(m, -6, current_timestamp)
These will result in the last six months. In my case, I want to print the last six month data. But the problem is if there is a data with the same date and different in the year will also result with these query eg (the above query returns the result of '2018-03-27 10:04:52.537' and if there is a data with '2017-03-27 10:04:52.537' will also come with the result). Can anyone help me?
here is my query
DECLARE #date6MonthAgo DATETIME = DATEADD(m, -6, current_timestamp)
DECLARE #totalCount INT = (SELECT COUNT(*)
FROM [PSA].[ProductionOrder]
WHERE CreatedDate >= #date6MonthAgo)
DECLARE #openCount INT = (SELECT COUNT(*)
FROM [PSA].[ProductionOrder]
WHERE DocumentStatusCode=7
AND CreatedDate >= #date6MonthAgo )
SELECT #date6MonthAgo, #totalCount, #openCount
Try something like this, after putting in the correct IDcolumn, just to verify for yourself the dates that are being returned
DECLARE #date6MonthAgo DATETIME = DATEADD(m, -6, current_timestamp);
SELECT #date6MonthAgo;
SELECT CreatedDate, keycolumnID
FROM [PSA].[ProductionOrder]
WHERE DocumentStatusCode=7
AND CreatedDate >= #date6MonthAgo
ORDER BY CreatedDate;
You can use this for find the last 6 month data from current date,
DECLARE #fromdate as datetime, #todate as datetime
set #fromdate = (select DATEADD(month, -6, getdate()))
set #todate = getdate()
SELECT CreatedDate, keycolumnID
FROM [PSA].[ProductionOrder]
WHERE DocumentStatusCode=7
AND cast(CreatedDate as date) between cast(#fromdate as date) and cast(#todate as date)
ORDER BY CreatedDate;
If you want find last 6 month date from a specific date, so you can set that date in #fromdate and #todate parameters like this,
set #fromdate = (select DATEADD(month, -6, #Yourdate))
set #todate = #Yourdate
I'm trying to create a report that gets records from a SQL Server database where the delivery date is today.
I've tried
select * from (tablename)
where delivery_date = getdate()
Although that didn't give me any errors, it didn't give me any records either.
I'm assuming it is because all dates are like:
2016-03-15 00:00:00.000
Perhaps, I need to truncate the date to remove the time-stamp and then try?
You can try a query like below
select * from (tablename)
where CAST(delivery_date as date) = CAST(getdate() as date)
Also if all delivery dates have time part like 00:00:00.000 for sure then
select * from (tablename)
where delivery_date = CAST(getdate() as date)
would work as good.
If delivery_date is always midnight (00:00:00.000), then compare it like this:
select * from (tablename)
where delivery_date = datediff(d, 0, getdate())
Using datediff like this is a quick way to truncate the time part of a datetime value.
I'd just create 2 params. One for StartTime and one for EndTime and use those in my query.
DECLARE #StartTime DATETIME,
#EndTime DATETIME
SET #StartTime = DATEDIFF(d,0,GETDATE())
SET #EndTime = DATEADD(d,1,#StartTime)
SELECT *
FROM [tablename]
WHERE delivery_date >= #StartTime
AND delivery_date < #EndTime
Try this:
DECLARE #Today DATETIME
SET #Today= CONVERT(date, getdate())
select * from (tablename)
where delivery_date = #Today
Yo need to remove the time part of the delivery_date field AND the GETDATE() value.
SELECT *
FROM (tablename)
WHERE DATEADD(dd, DATEDIFF(dd, 0, delivery_date), 0) = DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)
I want to filter data from SQL Server 2008 R2 using FromDate and ToDate with another 2 user input dates. I want query for that.I want to filter data such a way that If user input 2 dates or any date in between of them lies in FromDate or 'ToDate' or in between date then it filters data.
For i.e.
FromDate ToDate
15-11-2014 20-11-2014
if user input dates are 11-11-2014 and 20-12-2014. It means in between dates of this 2 dates lies in between FromDate and ToDate so it should return this record.
Now, if user input dates are 11-11-2014 and 14-11-2014. It means in between dates of this 2 dates does not lie in between FromDate and ToDate so it should not return this record.
It must match given dates and as well as in between dates.
you Can use this :
Where
DATEADD(dd, 0, DATEDIFF(dd, 0, FromDate)) > '15-11-2014'
and
DATEADD(dd, 0, DATEDIFF(dd, 0, ToDate)) < '20-11-2014'
please check the example, you just compare the parameter with both datetime column to extract the rows.
declare #table table(id int,frdt datetime, todt datetime)
insert into #table values (1,GETDATE()-20, GETDATE()-19)
,(1,GETDATE()-9, GETDATE()-8)
,(1,GETDATE()+20, GETDATE()+18)
,(1,GETDATE(), GETDATE()-1)
,(1,GETDATE()-20, GETDATE())
,(1,GETDATE()-10, GETDATE()+10 )
select * from #table
declare #frdt datetime = null , #todt datetime = getdate()-10
select #frdt, #todt,* from #table
where
(#frdt is null or #frdt between frdt and todt)
and
(#todt is null or #todt between frdt and todt)
select #frdt = GETDATE() , #todt = GETDATE()
select #frdt, #todt,* from #table
where
(#frdt is null or #frdt between frdt and todt)
and
(#todt is null or #todt between frdt and todt)
From what I understand from your question.
select 'a' A, CONVERT(date,'11/15/2014') FromDate, CONVERT(date, '11/20/2014') ToDate into #Temp
declare #frmDate date;
declare #toDate date;
set #frmDate = Convert(date, '11/11/2014');
set #toDate = CONVERT(Date, '12/20/2014');
select * from #Temp where FromDate>=#frmDate and ToDate<=#toDate
set #frmDate = Convert(date, '11/11/2014');
set #toDate = CONVERT(Date, '11/14/2014');
select * from #Temp where FromDate>=#frmDate and ToDate<=#toDate
Hope fully it help you :)
I am running a sql query that is omitting the day if the return count is 0. I want my query to return the day and a 0 count if the the count is 0. Snare I have is that if 0 were sold for the day, the day is omitted from my return results.
SELECT ISNULL([day],0) As [day], COUNT(ISNULL(Sold,0)) As [Sold]
FROM productionInfo
You're drawing information from a single table, productionInfo. If productionInfo has no rows with that date information (because there are no widgets sold on that date), how does it know what dates to use?
You might want to look at using a Numbers Table to get a row for each day of the month/year, then join that to productionInfo so you have a day value available, even if there was no production that day.
This will give you a dates table:
CREATE FUNCTION dbo.DatesTable (#startDate DATETIME, #endDate DATETIME)
RETURNS #retTable TABLE (DateValue DATETIME)
AS
BEGIN
DECLARE #currentDate DATETIME
SET #currentDate = #startDate
WHILE (DATEDIFF(dd, #currentDate, #endDate) >= 0)
BEGIN
INSERT INTO #retTable VALUES (#currentDate)
SET #currentDate = DATEADD(dd, 1, #currentDate)
END
RETURN
END
Then your query will look like:
SELECT dt.DateValue AS [day], COUNT(Sold) AS [Sold]
FROM dbo.DatesTable('2-1-2014', '2-10-2014') dt
LEFT JOIN productionInfo pi ON pi.day = dt.DateValue
GROUP BY dt.DateValue
Ok, I'm running query builder out of visual studio 2008. I'm trying to filter the results of the query by time; that is, I want to pull everything from the start of yesterday to noon yesterday.
I've been using GETDATE()-1 for yesterday, which pulls up a timestamp mm/dd/yyyy hh:mm:ss
however, it pulls the current time. to get it to run from the start of the day I appended the timestamp to remove the time itself, so it started at the beginning of the day:
convert(varchar(10), getdate()-1, 120)
so I'm using between to find the range, I have:
BETWEEN convert(varchar(10), getdate()-1, 120) AND // this is where I need it to cut off at noon.
I'm understanding that datetime is a data type here, so I tried subtracting the hours/minutes/seconds using date part, but datepart() only returns ints and doesn't affect the time.
thoughts? how do I get this to cut off at noon
Try this:
--Variables
declare #now datetime = getdate(),
#yesterday datetime
--Yesterday starting datetime
select #yesterday = convert(datetime, convert(date, dateadd(day,-1,#now)))
--Your query to filter between y'day start and y'day noon
--Note that between means inclusive boundary values. (or use >= and <=)
select * from yourTable
where dateCol between #yesteray and dateadd(hour,12,#yesterday)
DECLARE
#Min DATETIME
, #Max DATETIME
SELECT
#Min = DATEADD(DAY, -1, CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME))
, #Max = DATEADD(HOUR, 12, CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME))
SELECT *
FROM <Table> x
WHERE x.[Date] BETWEEN #Min AND #Max
SELECT * FROM T WHERE YourDate BETWEEN CAST(GETDATE()-1 As DATE) AND DATEADD(Hour, -12, CAST(CAST(GETDATE() As DATE) As DATETIME) )
Beware because BETWEEN will include lower and upper boundaries, so you can simply replace BETWEEN with x >= y and y < z if you don't want yesterday at 12:00 to be taken in account
between DateAdd(day, -1, cast(getdate() as date)) and DateAdd(hour, -12, cast(getdate() as date))
Edit: As mentioned in the comments, you can't use hours with a date, you have to cast it back to a datetime, thus:
between DateAdd(day, -1, cast(getdate() as date)) and DateAdd(hour, -12, cast(cast(getdate() as date) as datetime))
If you want to get the results from last 30 mins you need to use this. You can change MINUTE to HOUR too.
--Get now, hour and second included
DECLARE #NOW DATETIME = GETDATE()
--Get 30 mins from now
DECLARE #TranDate DATETIME
SET #TranDate = CONVERT(DATETIME, CONVERT(DATETIME, DATEADD(MINUTE,-30,#NOW)))
After That, add below code to your where statement,
AND TK.TransactionDate >= #TranDate