Convert hours into days:Hours format in SQL Server - sql

Create Table
(
id int identity(1,1),
WorkHours int
)
This is my table which stores working hours as integer. My requirement is to display work hours in DD:HH format. How is it possible?

To get it DD:HH format, you'll need to do some math as well as some 00 padding (or you get D:H) format:
select RIGHT('00' + CONVERT(VARCHAR, WorkHours / 24), 2) + ':' + RIGHT('00' + CONVERT(VARCHAR, WorkHours% 24), 2)
from MyTable

Integer division in SQL-Server is int1 / int2.
Modulo in SQL-Server is int1 % int2.
The function for formatting numbers in SQL-Server is FORMAT.
The string concatenation operator in SQL-Server is the non-standard +.
The query:
select format(workhours / 24, '00') + ':' + format(workhours % 24, '00')
from mytable;

with Calcs as
(
select id, floor(WorkHours/24) as DDField, (WorkHours/24)-floor(WorkHours/24) as HHField
from MyTable
)
select id, DDField + ':' + HHField
from Calcs

Related

How can I convert an integer like 3212007 to date 3-21-2007 uisng IBM DB2 SQL?

The dataset I inherited has a DATE column but the values in this column are integers of the form 3212007 which should be 03-21-2007. I can't get it back into date format.
I can convert the integer to a string using CAST(myinteger as varchar(8)) without difficulty. Then I can CAST that as date by CAST(CAST(myinteger as varchar(8)) as date) which gets me a date. The problem is that my integer is formatted as 'mmddyyyy' so for 3212007, I get 3212-01-07.
select TRANSACTION_DATE from MA_NORFOLK fetch first row only;
[returns: 3212007]
select CAST(TRANSACTION_DATE as VARCHAR) from MA_NORFOLK fetch first row only;
[returns: 3212007]
select CAST(CAST(TRANSACTION_DATE as varchar(8)) as date) from MA_NORFOLK fetch first row only;
[returns: 3212-01-07]
Other posts suggest using CONVERT command, but all I get are errors
"DATE" is not valid in the context where it is used..."
Could you please advise me?
Try this:
date(to_date(digits(dec(3212007, 8)), 'MMDDYYYY'))
If you may have one digit for month, there is an alternative:
select
date
(
case when substr(char_dt, 1, 2)='00'
then translate('EFGH-0D-0C', char_dt, 'ABCDEFGH')
else translate('EFGH-AB-CD', char_dt, 'ABCDEFGH')
end
) dt, char_dt
from
(
select digits(dec(i, 8)) char_dt
from table(values 3212007, 312007) t(i)
) t;
DT CHAR_DT
---------- --------
2007-03-21 03212007
2007-01-03 00312007
This works (at least in MS SQL Server):
SELECT CAST(CONCAT( RIGHT(3212007,4),'-',
(3212007 / 1000000), '-', ((3212007 % 1000000) / 10000)) AS date)
The trick is that you don't know if you will have a single digit, or two-digit month, so you have to start with getting just the right 4 characters as the year. Then by using combinations of modulo and integer divide, you can parse out the month and day.
Of course, you will want to substitute your actual date column for the sample data that I used above.
I think this may works well:
create table #temp(
date int
)
insert into #temp (date)
values(3212007),
(12032019)
select
case when len(cast(date as varchar)) = 7
then
'0' + left(cast(date as varchar), 1) + '-' + substring(cast(date as varchar), 2,2) + '-' + right(cast(date as varchar), 4)
else left(cast(date as varchar), 2) + '-' + substring(cast(date as varchar), 3,2) + '-' + right(cast(date as varchar), 4) end
from #temp

Trying to round the results of a sql query to 2 decimals

In the following query, I'm trying to return the data with 2 decimal places (.00) for the SUM line:
SELECT
CONVERT(varchar, YEAR(COALESCE(release_date, requested_date)))
+ RIGHT('00' + CONVERT(varchar, MONTH(COALESCE(release_date, requested_date))), 2) AS yrmnth,
salesrep,
customer_name,
SUM(price_per_ea * COALESCE(open_release_qty, open_order_qty)) AS ext_price
you could use convert for take control over the format
SELECT
CONVERT(VARCHAR, YEAR(COALESCE(release_date, requested_date)))
+ RIGHT('00' + CONVERT(VARCHAR,
MONTH(COALESCE(release_date, requested_date))),2) as yrmnth
,salesrep
,customer_name
, Convert(decimal(12,2),
SUM(price_per_ea * COALESCE(open_release_qty, open_order_qty))) as ext_price
Use the round function in your select:
round(SUM(price_per_ea * COALESCE(open_release_qty, open_order_qty)),2)

Convert string to Datetime

I've received a flat file and after parsing and inserting it in a table. I've a column which has dates in a format yyyyMMddhhmmss
Here, yyyy is year, MM is month, dd is day, hh is hours, mm is minute and ss is seconds part
I'm trying to convert this to DateTime type as mentioned below but not working for me
SELECT CAST(StrDate as DateTime) FROM [dbo].[Mytable]
For example:
Column has a value 20150121190941 in Varchar format and it should be converted to DateTime as 2015-01-21 19:09:41.000
I apologize if it's a duplicate one.
You can use select DATETIMEFROMPARTS ( year, month, day, hour, minute, seconds, milliseconds )
declare #dt nvarchar(25) = '20150121190941'
select datetimefromparts(left(#dt,4), substring(#dt,5,2), substring(#dt,7,2),substring(#dt,9,2), substring(#dt,11,2), substring(#dt,13,2), '000')
SQL Server readily recognizes YYYYMMDD as a date. So, converting the first 8 characters to a date is easy. Alas, I don't think there is a time representation without colons.
So, here is one rather brutal method:
select (convert(datetime, left(StrDate, 8)) +
convert(time, substring(StrDate, 9, 2 ) + ':' + substring(StrDate, 11, 2 ) + ':' + substring(StrDate, 13, 2 )
)
)
Declare #dt varchar(50)
set #dt=20150121190941
create table tblDateTbl
(
col1 datetime
)
insert into dt (col1)
select SUBSTRING(#dt,1,4) + '-' + SUBSTRING(#dt,5,2) + '-' + SUBSTRING(#dt,7,2)+ ' ' + SUBSTRING(#dt,9,2)+ ':' + SUBSTRING(#dt,11,2)+ ':' + SUBSTRING(#dt,13,2)+ '.000'

SQL conversion from varchar to datetime

One of the columns of my SQL Server table is mm:ss of varchar type where mm = minutes and ss = seconds.
I need to get the average of that column.
Should I convert that column to datetime format first? If so can you tell me how? If not can you tell me what I should do?
Here is my failed attempt to convert it to datetime :
SELECT CONVERT(DATETIME, '2014-01-01 '+Pace+':00', 108)
Where pace is a varchar like 23:05
If you want the average, I would convert the column to number of seconds and work with that:
select avg(pace_secs) as average_in_seconds
from (select cast(left(pace, 2) as int) * 60 + cast(right(pace, 2) as int) as pace_secs
from t
) t;
If you want this back in the format, then you can do:
select right('00' + cast(avg(pace_secs) / 60 as int), 2) + ':' +
right('00' + avg(page_secs) % 60), 2)
from (select cast(left(pace, 2) as int) * 60 + cast(right(pace, 2) as int) as pace_secs
from t
) t;
declare #pace varchar(20) = '23:05 ';
SELECT cast( '2014-01-01 '+cast(#pace as varchar(5))+':00' as datetime)
For SQL2012 and later
SELECT
FORMAT(DATEADD(second,AVG(DATEDIFF(second,0,'00:'+[Pace])),0),'mm:ss')
FROM MyTable

Convert four Digit number into hour format SQL

I have looked into Cast and Convert, but I cannot find a way to do this. I need to convert four digits into an hour format. For instance, 0800 would become 8:00 or 1530 would become 15:30. I cannot use functions, I'm using a InterSystem's CacheSQL. Any suggestions? Thanks in advance!
EDIT:
If it is any more convenient, I can just divide the four digits by one hundred to get values like 15 from original 1500, or 8.30 from 0830. Does this make converting to hour:minute format easier?
For CacheSQL, you can do this:
SELECT {fn TRIM(LEADING '0' FROM LEFT(col_name, 2) || ':' || RIGHT(col_name, 2)) }
FROM table_name
In SQL Server 2008, given data that looks like
create table #data
(
HHMM int not null ,
)
insert #data values ( 0800 )
insert #data values ( 0815 )
insert #data values ( 1037 )
insert #data values ( 2359 )
You can say:
select * ,
strTime = right( '0' + convert(varchar, HHMM / 100 ) , 2 )
+ ':'
+ right( '0' + convert(varchar, HHMM % 100 ) , 2 ) ,
myTime = convert(time ,
right( '0' + convert(varchar, HHMM / 100 ) , 2 )
+ ':'
+ right( '0' + convert(varchar, HHMM % 100 ) , 2 ) ,
120
)
from #data
Other SQL implementations likely have similar functionality.
In earlier versions of SQL Server that lack the time datatype, just use datetime, thus:
select * ,
strTime = right( '0' + convert(varchar, HHMM / 100 ) , 2 )
+ ':'
+ right( '0' + convert(varchar, HHMM % 100 ) , 2 ) ,
myTime = convert(datetime,
right( '0' + convert(varchar, HHMM / 100 ) , 2 )
+ ':'
+ right( '0' + convert(varchar, HHMM % 100 ) , 2 ) ,
120
)
from #data
You'll get a datetime value that is 1 Jan 1900 with the desired time-of-day.
Well, if it is something like Oracle you might have a try with the to_date() function.
Read more here.
Example:
SELECT to_date(yourColumn, 'HH24MI') FROM ...
EDIT (why? see comments): If necessary (I'm actually not familiar with Oracle) you can wrap another function like TIME() around it.
SELECT TIME(to_date(yourColumn, 'HH24MI')) FROM ...
Read more about TIME() here.
</EDIT>
In MySQL the equivalent would be the STR_TO_DATE() function:
SELECT STR_TO_DATE(yourColumn, '%H%i') FROM ...
Read about STR_TO_DATE() and its parameters under the DATE_FORMAT() function.
left( case when (EndTime / 100) < 10 then ('0'+ convert(varchar, EndTime / 100 )) else convert(varchar, EndTime / 100 ) end, 2 )
+ ':'
+ right( '0' + convert(varchar, EndTime % 100 ) , 2 )