Order by time part only - sql-server

When I select time in SQL it is returned as 2011-02-25 21:17:33.933. But I need only the time part. How can I do this? I'm trying to: order by "Onlie Duration" DESc , but need it to be ordered by time

You can do something like this:
SELECT time_column FROM dbo.table
ORDER BY CONVERT(time, time_column)

You can get only the time part using:
select convert(char,[YourDateColumn],108) from [YourTable]
Sorting your data based on time can be done by ordering using:
select * from [YourTable] order by convert(char,[yourDateColumn],108)
The downside to this is that, sorting with just the time when there are dates for different days will mix the time for the various days.

Use Convert function
SELECT * FROM MyTable
ORDER BY CONVERT(varchar(10), TimeField, 108)
UPD Or using DATEDIFF:
SELECT * FROM MyTable
ORDER BY DATEDIFF(MILLISECOND, CAST(TimeField AS DATE), TimeField)

Related

Datediff last and previous dates SQL

I'm learning SQL, for an exercise I have to several things.
I'm making a query to compare the most recent orderdate with the orderdate before. I want to use a correlated subquery for this. I have already made it using a Cross Apply and Window functions.
At the moment I have this:
select
b1.klantnr,
DATEDIFF(D, (Select MAX(b1.Besteldatum)),
(Select MAX(b1.Besteldatum)
where besteldatum not in (Select MAX(b1.besteldatum)))) as verschil
from
bestelling b1
group by
b1.klantnr, b1.besteldatum
I only get null values in the datediff column. It should return this:
Results
I'm using SQL Server 2014 Management Studio.
Any help appreciated.
Here is one simple way:
select datediff(day, min(bs.Besteldatum), max(bs.Besteldatum)) as most_recent_diff
from (select top (2) bs.*
from bestelling bs
order by bs.Besteldatum
) bs;
This uses a subquery, but not a correlated subquery. Should have really good performance, if you have an index on bestselling(Besteldatum).
A correlated subquery way.
select top 1 bs.*,datediff(day,
(select max(bs1.Besteldatum)
from bestelling bs1
where bs1.Besteldatum<bs.Besteldatum),
bs.Besteldatum
) as diff
from bestelling bs
order by bs.Besteldatum desc
This gives only the difference between latest date and the date preceding it. If you need all records remove top 1 from the query.

SQL Server banding timepoints based on value

I have audit data captured over time points which I would like to aggregate up to display where the value was the same over a period of time using SQL Server 2014.
Taking the below example data
I would like to transpose it to this ideally without using a cursor - you will see that the output is recording the time period where the value is the same and as such, the same value can be repeated over different periods (seen in rows 3 and 6).
I have been looking at LEAD() and LAG() as potential solutions, however I cannot fathom out how to make this work in order to band by time for the same value
Any direction would be gratefully received
In case the column [value] doesnt contain distinct number, you can use this query
SELECT start,end,value
FROM (SELECT MIN(ts) start
,MAX(ts) end
,value
,C
FROM (SELECT ts
,value
,(ROW_NUMBER() OVER (ORDER BY ts)
- ROW_NUMBER() OVER (PARTITION BY value ORDER BY ts)) C
FROM YourTable) x
GROUP BY value,C) y ORDER BY start
After seeing your further comments, the below is obviously of no use...
I think you may be over complicating it. If you are looking for the minimum and maximum ts per distinct value, then you can just use MIN & MAX and group by the Value, e.g.
SELECT MIN(ts) AS [Start] ,
MAX(ts) AS [End] ,
Value
FROM Table
GROUP BY Value

A tricky query to update the table with values of another table

This question is an extension of my previous one available at Unable know the exception in query.
This time I've Another table named breaks.
And it looks like below.
I'm able to get the column sum using the below query.
SELECT DATEADD(SECOND, SUM(DATEDIFF(SECOND, '19000101', TotalBreakTime)), '19000101') where
where USERID = 0138039 AND CONVERT(Date, StartTime) = CONVERT(Date, GETDATE()))
as t FROM BreaksTable;
My second table looks like below.
This time, I want to update the breaks column with the sum of the totalbreaktime from Breaks table(the first screenshot) and the condition has to be the date is to be current day.
I'm really unable to understand how to do this.
You need MERGE:
MERGE SecondTable as target
USING (
SELECT USERID,
SUM(DATEDIFF(SECOND, '19000101', TotalBreakTime)) as ColumnWithBreaksCount
FROM BreaksTable
where CONVERT(Date, StartTime) = CONVERT(Date, GETDATE()))
GROUP BY USERID) as source
ON target.USERID = source.USERID
WHEN MATCHED THEN UPDATE
SET BREAKS = source.ColumnWithBreaksCount
But this will work only if you have only one column for each USERID in your secondtable, else you need to add another key kolumn in ON part of query, which will help to make rows unique.

How to calculate the days between 2 dates from 2 successive IDs

I need some help to create a new column in a database in SQL Server 2008.
I have the following data table
Please have a look at a snapshot of my table
Table
In the blank column I would like to put the difference between the current status date and the next status' date. And for the last ID_Status for each ID_Ticket I would like to have the difference between now date and it's date !
I hope that you got an idea about my problem.
Please share if you have any ideas about how to do .
Many thanks
kind regards
You didn't specify your RDBMS, so I'll post an answer for both since they are almost identical :
SQL-Server :
SELECT ss.id_ticket,ss.id_status,ss.date_status,
DATEDIFF(day,ss.date_status,ss.coalesce(ss.next_date,GETDATE())) as diffStatus
FROM (
SELECT t.*,
(SELECT TOP 1 s.date_status FROM YourTable s
WHERE t.id_ticket = s.id_ticket and s.date_status > t.date_status
ORDER BY s.date_status ASC) as next_date)
FROM YourTable t) ss
MySQL :
SELECT ss.id_ticket,ss.id_status,ss.date_status,
DATEDIFF(ss.date_status,ss.coalesce(ss.next_date,now())) as diffStatus
FROM (
SELECT t.*,
(SELECT s.date_status FROM YourTable s
WHERE t.id_ticket = s.id_ticket and s.date_status > t.date_status
ORDER BY s.date_status ASC limit 1) as next_date)
FROM YourTable t) ss
This basically first use a correlated sub query to bring the next date using limit/top , and then wrap it with another select to calculate the difference between them using DATEDIFF().
Basically it can be done without the wrapping query, but it won't be readable since the correlated query will be inside the DATEDIFF() function, so I prefer this way.

Order By not working on datetime 101 format

Create table #temp
(
OrderDate datetime
)
insert into #temp values ('01/21/2015'),('01/20/2014'),('11/12/2013')
select distinct convert(varchar(10),orderdate,101) as OrderDate from #temp
order by convert(varchar(10),orderdate,101) asc
The above query gives me the result like below:
OrderDate
01/20/2014
01/21/2015
11/12/2013
But I want the result like below:
OrderDate
11/12/2013
01/20/2014
01/21/2015
The above is just a sample on which I am trying to do sorting on format 101. In my actual query I need to use distinct keyword and also the columns will come dynamically in the select statement by using parameter.
I can't use group by in my actual query.
Please help.
UPDATE
Referring to your comments the only way I've managed to get the UNIQUE results with only one column orderdate converted to VARCHAR 101 representation while still sorting it according to DATETIME sort order, was using a little workaround with GROUP BY clause:
SELECT
CONVERT(VARCHAR(10), A.OrderDate, 101) as orderdate
FROM
#temp AS A
GROUP BY
CONVERT(VARCHAR(10), A.OrderDate, 101)
ORDER BY
MAX(A.OrderDate) ASC
MAX(A.OrderDate) should always give you the exactly equal value to the value of every group, so it shouldn't be an improper way - I've put a working example with repeats under the following link on SQL Fiddle.
Still maybe the previous two-columned solution would happen to occur helpful:
select distinct
convert(varchar(10),orderdate,101) as OrderDateConverted,
orderdate
from
#temp
order by
orderdate asc
The above query sorts your query results according to DATETIME datatype whereas order by convert(varchar(10),orderdate,101) caused the alphanumeric sort order.
You can use subQuery as follows to solve the issue.
SELECT t.OrderDate FROM (
SELECT distinct Convert(VARCHAR(10), orderdate, 101) AS OrderDate
from #temp ) t
order by cast(t.OrderDate AS DATETIME) asc

Resources