Trying to convert seconds to a minute:seconds format.
e.g. 207 seconds would be 3:27
I have a table with column length that has the length of songs stored in seconds.
Using this query almost works, however, when a song should be 3:03 it will instead show 3:3
select concat(Length/60, ':', Length%60) as Length from songs
SELECT Convert(nvarchar, (Length/60)) + ':' + RIGHT('0' + Convert(nvarchar, Length%60), 2) as Length from songs
I build this using a varaible since I didn't have your table, but try this:
declare #length int = 207
select concat(#Length/60, ':', case len(#Length%60) when 1 then '0' else '' end, #Length%60) as [leng]
You can use dateadd to do that:
select convert(varchar, dateadd(second, 187, 0), 108)
This returns "00:03:07" so you can cut away hours if you don't need them.
Related
I have a table with columns Hour and Minute, both containing an integer. (There are other columns as well). Now, I want to create a view from this table and I need to combine these two columns' data into one column with a ':' symbol. For example, if a record has 8 for Hour, 10 for Minute, the combined column should contain 08:10. One digit numbers need to be followed by a leading 0, which initially does not exist in Hour and Minute columns.
I was successfully able to convert the integer to varchar and concatenate the numbers with ':' with the following SQL command
/* Combined Column name "Time" */
SELECT
Cast([Hour] as varchar) + ':' + Cast([Minute] as varchar) As Time
FROM Table1
but I am not sure how I can add leading 0 to this only if the number is one digit. Can someone please help me with this? Thank you.
One Other Approach :
SELECT
(CASE WHEN LEN(Cast([Hour] as varchar))=1 THEN '0'+Cast([Hour] as varchar) ELSE Cast([Hour] as varchar) END) + ':' +
(CASE WHEN LEN(Cast([Minute] as varchar))=1 THEN '0'+Cast([Minute] as varchar) ELSE Cast([Minute] as varchar) END) As Time
FROM Table1
Hope its helps you ! :)
Use timefromparts() (SQL Server 2012+) to create a proper time value:
select timefromparts(hour, minute, 0, 0, 0)
You can then format this as a string, if that is what you really want to do:
select convert(varchar(5), timefromparts(hour, minute, 0, 0, 0))
You can create scalar function to pad characters:
CREATE FUNCTION dbo.PadNumbersOnLeft (#NumberInput INT, #NoOfCharsToPad tinyint)
RETURNS VARCHAR(250)
AS BEGIN
DECLARE #ResultString VARCHAR(250)
SET #ResultString = LTRIM(#NumberInput)
IF(#NoOfCharsToPad > LEN(#ResultString))
SET #ResultString = REPLICATE('0', #NoOfCharsToPad - LEN(#ResultString)) + #ResultString;
RETURN #ResultString;
END;
And here is the example how to use this:
declare #hour int = 8
declare #minute int = 35
select
[dbo].[PadNumbersOnLeft] (#hour, 2) + ':' + [dbo].[PadNumbersOnLeft] (#minute, 2)
You can replace your columns names with #hour and #minute variables.
Trying to output something like:
2016,11
Using this:
SELECT
CONVERT(VARCHAR(20),YEAR(GETDATE()) + ',' + MONTH(GETDATE())) AS YearMonth
Am I missing something in convert? Because I am getting this error:
Conversion failed when converting the varchar value ',' to data type
int.
Thanks
Try this.
SELECT
CONVERT(VARCHAR(20),YEAR(GETDATE())) + ',' + CONVERT(VARCHAR(20), MONTH(GETDATE())) AS YearMonth
You might use CONVERT with 112 to reach a string without delimiters ("20161110"). Converting this to VARCHAR(*6*) will implicitly cut the day. One (in most cases positiv) side-effect: You will get a low month zero padded (e.g. 2016,04). Then I use STUFF to insert the ,:
SELECT STUFF(CONVERT(VARCHAR(6),GETDATE(),112),5,0,',')
If you do not like the zero padded month, you could replace the 0 in STUFF like this:
DECLARE #d DATETIME={d'2016-04-05'};
SELECT STUFF(CONVERT(VARCHAR(6),#d,112),5,CASE WHEN MONTH(#d)<10 THEN 1 ELSE 0 END,',')
You are missing converting the output of MONTH() to a string. Here is one method:
select datename(year, getdate()) + ',' + cast(month(getdate()) as varchar(255)) as YearMonth
datename() is convenient because it returns a string. Unfortunately, for month it returns the name of the month, rather than the number.
You could also do:
select replace(convert(varchar(7), getdate(), 120), '-', ',')
Or use format() in SQL Server 2012+:
select format(getdate(), 'yyyy,MM')
I Have Minutes as 1064 in a column called 'Efforts_in_minutes' and I need the Output in the format of HH:MM (i.e) 17:44. I have tried the below Query
SELECT Cast(Round(Total_Effort_in_Minutes / 60, 0, 2) AS VARCHAR)
+ ':'
+ Cast(Total_Effort_in_Minutes % 60 AS VARCHAR(2))
FROM PPS
I got the output as 17.000000:44 but What i Need is 17:44
Please advice how to achieve that.
The use of the Round function is unnecessary. Just do integer division:
select CAST(CAST(Total_Effort_in_Minutes AS INT) / 60 AS VARCHAR)
+ ':' + CAST(Total_Effort_in_Minutes % 60 AS VARCHAR(2) )
If your column Total_Effort_in_Minutes already has an integer data type, then you can simplify to:
select CAST(Total_Effort_in_Minutes / 60 AS VARCHAR)
+ ':' + CAST(Total_Effort_in_Minutes % 60 AS VARCHAR(2) )
If you need the minute part to be left-padded with zero to get at least 2 digits, then:
select RIGHT('0' + CAST(CAST(Total_Effort_in_Minutes AS INT) / 60 AS VARCHAR), 2)
+ ':' + CAST(Total_Effort_in_Minutes % 60 AS VARCHAR(2) )
SELECT DATEADD(MI,Total_Effort_in_Minutes,TIMEFROMPARTS(0,0,0,0,0))
FROM PPS
Best practice: The client should decide how to represent the time based on the locale, to allow for variants such as 24H clock vs AM/PM.
Please see this link: https://stackoverflow.com/a/19887500/6298495
Creating an inline function is a good solution provided in the link.
Just for fun:
SELECT CONVERT(CHAR(5), DATEADD(mi, 1064, 0), 8)
There is a column in my Table. In which we are storing string value in format 'HH:MM'.During fetching records with this table every things works ok with
DATEDIFF(MINUTE, '00:00', ColumnName)
Problem is when we have Value greater than 23:59.
Its showing error like
Conversion failed when converting date and/or time from character string.
Can anybody suggest me the right approach for achieving this scenario.
If you are storing the value as something other than a time, why not just store the number of minutes and convert to whatever format you want on output?
Otherwise, I would suggest that you simply convert the value to minutes:
select (cast(left(ColumnName, 2) as int) * 60 +
cast(right(ColumnName, 2) as int)
) as Minutes
If you are not using date/time values, there is no requirement for using the functions specifically designed for them.
EDIT:
To handle hours longer than 99, use charindex():
select (cast(left(ColumnName, charindex(':', ColumnName) - 1) as int) * 60 +
cast(right(ColumnName, 2) as int)
) as Minutes
So it sounds like your saving the length of a time period. Try storing it in minutes. My query can handle numbers of different lengths since it's based on the colon.
DECLARE #yourTable TABLE (ColumnName VARCHAR(10));
INSERT INTO #yourTable
VALUES ('100:00'),
('24:20');
SELECT ColumnName,
(hr * 60) + minut AS time_period_in_minutes
FROM #yourTable
CROSS APPLY (SELECT CAST(SUBSTRING(ColumnName,0,CHARINDEX(':',ColumnName)) AS INT),
CAST(SUBSTRING(ColumnName,CHARINDEX(':',ColumnName) + 1,LEN(ColumnName)) AS INT)) CA(hr,minut)
Results:
ColumnName time_period_in_minutes
---------- ----------------------
100:00 6000
24:20 1460
Try to this
select DATEDIFF(MINUTE, '00:00', case when ISDATE(ColumnName)=0 then '00:00' else ColumnName end )
I am looking for some help in regards to the format that I want my data outputted.
Below is a snippet of the code I am using. It is currently converting the value from the database in seconds and outputting it like
1d 12:05:52
I want it to output the information so it calculates the day in the hours, so basically dropping the '1d' like below
36:05:52
CAST(FLOOR([Running] / 86400) AS VARCHAR(10))+'d ' + CONVERT(VARCHAR(8), DATEADD(SECOND, [Running], '19000101'), 8) AS [Running]
Can someone please point me in the right direction using the code above?
Thanks in advance for your help.
This should work:
SELECT
CASE WHEN [Running]/3600 <= 9 THEN '0' ELSE '' END +
CONVERT(VARCHAR(10),[Running]/3600)+':'+
RIGHT('00'+CONVERT(VARCHAR(2),([Running]%3600)/60),2)+':'+
RIGHT('00'+CONVERT(VARCHAR(2),[Running]%60),2) AS [Running]
I tested it using this:
DECLARE #Running int
SET #Running = 60*60*24*30 + 60*3 + 3 -- should output 720:03:03
SELECT
CASE WHEN #Running/3600 <= 9 THEN '0' ELSE '' END +
CONVERT(VARCHAR(10),#Running/3600)+':'+
RIGHT('00'+CONVERT(VARCHAR(2),(#Running%3600)/60),2)+':'+
RIGHT('00'+CONVERT(VARCHAR(2),#Running%60),2) AS [Running]
Output:
Running
----------------
720:03:03
(1 row(s) affected)
As #Hadi said in his comment, you can use the TimeSpan object in VB.Net (you've tagged the question with this so it seems reasonable to suggest), but you could also use this bit of SQL instead, which I think is slightly simpler than the other suggestion :
CAST(CAST(FLOOR([Running] / 3600) AS INT) AS VARCHAR) +
RIGHT(CONVERT(VARCHAR, DATEADD(SECOND, [Running], '1900-01-01'), 108), 6) as [Running]
Here's one more way to do it, good answers here already tho. :)
-- Setting param for testing purposes, replace this with actual column in the formula below
DECLARE #SECS INT
SET #SECS = 3787*26
-- Your original formula for 'D' value
SELECT CAST(FLOOR(#SECS / 86400) AS VARCHAR(10))+'d ' + CONVERT(VARCHAR(8), DATEADD(SECOND, #SECS, '19000101'), 8)
-- New one for HH:MM:SS
SELECT CAST(#SECS/3600 AS VARCHAR(20))+':'+RIGHT('0'+CAST((#SECS%3600)/60 AS VARCHAR(2)),2)+':'+RIGHT('0'+CAST(#SECS%60 AS VARCHAR(2)),2)