Get age from record in table: T-SQL - tsql

So each record on my table has a datetime timestamp column.
How do I return the age (in hours), of these records in the database?
Thank you!

select DATEDIFF(hour,timestamp,getdate()) as hours_old
from myTable

datediff(hour,[Your Column], getdate())
http://msdn.microsoft.com/en-us/library/ms189794.aspx

Use the datediff function.
select datediff(hour, getdate(), dob) as age
from ...

Since datediff(hour,'2000-01-01 00:59','2000-01-01 01:00') returns 1, due to the (counterintuitive) way datediff works, you may want something more accurate:
select DATEDIFF(minute,the_timestamp,getdate()) / 60
from TheTable

Related

SQL Server and index and null parameters

I have the below stored procedure that run against 2,304,697 records :
#startdate DATETIME NULL,
#enddate DATETIME NULL,
#drilldown VARCHAR(20) NULL
AS
BEGIN
SELECT
DATENAME(YEAR, ReceivingTime) as Year,
MAX(DATENAME(MONTH, ReceivingTime)) AS Month,
ProductionLocation,
CAST(COUNT(*) * 100.0 / SUM(COUNT(*) * 100) OVER (PARTITION BY DATENAME(YEAR, ReceivingTime), MONTH(ReceivingTime)) AS DECIMAL(10,2)) AS TotalsByMonth,
CAST(COUNT(*) * 100.0 / SUM(COUNT(*) * 100) OVER (PARTITION BY DATENAME(YEAR, ReceivingTime)) AS DECIMAL(10, 2)) AS TotalsByYear
FROM
Jobs_analytics
WHERE
ProductionLocation IS NOT NULL
AND ((ReceivingTime BETWEEN dbo.cleanStartDate(#startdate) AND dbo.cleanEndDate(#enddate))
AND #startdate IS NULL)
OR ((YEAR(ReceivingTime) = #drilldown) AND #drilldown IS NULL)
GROUP BY
DATENAME(YEAR, ReceivingTime),
DATEPART(MONTH, ReceivingTime), ProductionLocation
ORDER BY
DATENAME(YEAR, ReceivingTime),
DATEPART(MONTH, ReceivingTime)
The query works well in that it returns a data set in about 8 seconds. But I like to get the speed better So I added the below index:
CREATE INDEX RecDateTime
ON Jobs_analytics(RecDateTime, ProductionLocation)
go
however that really didn't improve anything. So I ran the execution plan and I notice that the my index is being used and the cost was 35% and my sort was at 6%.
So I reworked my where clause from this:
WHERE ProductionLocation IS NOT NULL AND
((ReceivingTime BETWEEN dbo.cleanStartDate(#startdate) and dbo.cleanEndDate(#enddate) ) AND #drilldown IS NULL)
OR ((YEAR(ReceivingTime) = #drilldown) AND #startdate IS NULL)
to this:
WHERE ProductionLocation IS NOT NULL AND
ReceivingTime BETWEEN dbo.cleanStartDate('2018-07-01') and dbo.cleanEndDate('2019-08-25')
and I got the query to run in a second. As you can see there is no more filter and the cost on the cluster is at 3%..( something I did not realize)
The NULL parameter checks are for a report that sometimes will have null values set. so I don't have to maintain two stored procedures. I can write a second stored procedure and just remove the where clause items but I rather not. is there any index or changes to my query that anyone could suggest that might help
Thanks
Mike
Okay if anyone comes across this this is what I found out:
I was testing the wrong parameter for null values within the OR
clause.
I have function that adds the hh:mm:ss to a date that was also
causing me problem.
I fixed both those items and the query runs in about a second.

Find most recent date

I have o table name table_1 with 4 columns id, text, fromDate, toDate. The table represents the working experience.I want to create a function which will return the row with columns id, text where the employee worked more recently. This means I need column toDate to be closest to today.
Here is a demonstration of my code:
Select (abs("toDate"-now())) as date_diff
from table_1
Select id,text
from table_1
where (abs("toDate"-now()))=select min(date_diff)
Is this correct or is there something better I can do?
I wil try something like this:
Select id,text
from table_1
where "toDate" = ( select max ("toDate") from table_1 )
It will provide you the latest "toDate" value.
Try this:
select * from table_1
order by to_date desc
limit 1

Get min date in Postgres

How do I get the min date of a timestamp field?
I tried to use
select min(myDatefield) from mytable
but this code doesn't returns the minimum date, but all dates.
Any clue why?
Try this, this might work for you.
SELECT *
FROM
(SELECT MCSSP_AUDIT_ACTIVITY_DATE
FROM MCSSP_MESG_AUDIT_BK
ORDER BY MCSSP_AUDIT_ACTIVITY_DATE ASC
)
WHERE rownum = 1;

TSQL - Control a number sequence

Im a new in TSQL.
I have a table with a field called ODOMETER of a vehicle. I have to get the quantity of km in a period of time from 1st of the month to the end.
SELECT MAX(Odometer) - MIN(Odometer) as TotalKm FROM Table
This will work in ideal test scenary, but the Odomometer can be reset to 0 in anytime.
Someone can help to solve my problem, thank you.
I'm working with MS SQL 2012
EXAMPLE of records:
Date Odometer value
datetime var, 37210
datetime var, 37340
datetime var, 0
datetime var, 220
Try something like this using the LAG. There are other ways, but this should be easy.
EDIT: Changing the sample data to include records outside of the desired month range. Also simplifying that Reading for easy hand calc. Will shows a second option as siggested by OP.
DECLARE #tbl TABLE (stamp DATETIME, Reading INT)
INSERT INTO #tbl VALUES
('02/28/2014',0)
,('03/01/2014',10)
,('03/10/2014',20)
,('03/22/2014',0)
,('03/30/2014',10)
,('03/31/2014',20)
,('04/01/2014',30)
--Original solution with WHERE on the "outer" SELECT.
--This give a result of 40 as it include the change of 10 between 2/28 and 3/31.
;WITH cte AS (
SELECT Reading
,LAG(Reading,1,Reading) OVER (ORDER BY stamp ASC) LastReading
,Reading - LAG(Reading,1,Reading) OVER (ORDER BY stamp ASC) ChangeSinceLastReading
,CONVERT(date, stamp) stamp
FROM #tbl
)
SELECT SUM(CASE WHEN Reading = 0 THEN 0 ELSE ChangeSinceLastReading END)
FROM cte
WHERE stamp BETWEEN '03/01/2014' AND '03/31/2014'
--Second option with WHERE on the "inner" SELECT (within the CTE)
--This give a result of 30 as it include the change of 10 between 2/28 and 3/31 is by the filtered lag.
;WITH cte AS (
SELECT Reading
,LAG(Reading,1,Reading) OVER (ORDER BY stamp ASC) LastReading
,Reading - LAG(Reading,1,Reading) OVER (ORDER BY stamp ASC) ChangeSinceLastReading
,CONVERT(date, stamp) stamp
FROM #tbl
WHERE stamp BETWEEN '03/01/2014' AND '03/31/2014'
)
SELECT SUM(CASE WHEN Reading = 0 THEN 0 ELSE ChangeSinceLastReading END)
FROM cte
I think Karl solution using LAG is better than mine, but anyway:
;WITH [Rows] AS
(
SELECT o1.[Date], o1.[Value] as CurrentValue,
(SELECT TOP 1 o2.[Value]
FROM #tbl o2 WHERE o1.[Date] < o2.[Date]) as NextValue
FROM #tbl o1
)
SELECT SUM (CASE WHEN [NextValue] IS NULL OR [NextValue] < [CurrentValue] THEN 0 ELSE [NextValue] - [CurrentValue] END )
FROM [Rows]

select using "current_date" as criteria?

If I've been recording data with timestamp. How can I query for today's data? Something similar to this example.
SELECT * FROM table WHERE recorded_time = current_date;
Thanks
DATE_TRUNC('day', recorded_time) = CURRENT_DATE
should do it.