Archive for the ‘SQL DateTime’ Category

h1

SQL SERVER: Get Result ORDER BY Time regardless Date on SQL DateTime column

03/24/2009


Usually we save Time with Dates in DATETIME column.
Today, I came across situation, where I need to sort my result set by Time, regardless the Date.


Let’s see Example

I have some sample data like this:

DECLARE @Data TABLE(dt DATETIME)

INSERT INTO @Data(dt)
SELECT ‘2008-12-05 04:00:00.000’
UNION ALL
SELECT ‘2008-12-10 10:00:00.000’
UNION ALL
SELECT ‘2009-03-01 08:00:00.000’
UNION ALL
SELECT ‘2009-03-02 07:15:00.000’
UNION ALL
SELECT ‘2009-03-10 08:50:00.000’
UNION ALL
SELECT ‘2008-12-31 23:00:00.000’
UNION ALL
SELECT ‘2009-05-01 21:10:00.000’

SELECT *
FROM @Data
Now we need output like this:

Get Result Order BY Time regardless Date on DateTime column

Get Result Order BY Time regardless Date on DateTime column


I found very quick solution for this. You can create query as follows:

SELECT *
FROM @Data
ORDER BY Convert(VARCHAR, dt,108)


Let me know if it helps you in any way.

h1

SQL SERVER: Display Minutes in Hour Format like HH:MM

03/23/2009


Usually, we are saving Hours in Minute Format. So if user has entered
Hour: 2 Minutes: 15. We will save 135 Minutes in Database, so we can manipulate it easily.


Now we need a report in which we need to display this minutes in HH:MM format as user has entered.

This is very simple, lets see:

DECLARE @t TABLE(Minutes INT)
INSERT INTO @t
SELECT 120
UNION ALL
SELECT 135
UNION ALL
SELECT 135
UNION ALL
SELECT 1440
UNION ALL
SELECT 640
UNION ALL
SELECT 720

SELECT Minutes / 60 as Hours,
Minutes % 60 AS Minutes
FROM @t

Let me know if it helps you in any way.