SQl Query to calculate Total in HH:MM Format - sql-server-2008

I have a table(production) which is having a column with name TimeSpent, the datatype of this column is varchar and it stores data in HH:MM format example 10:23,14:59,11:00 etc.I want to write a query in sql which will sum this and give me a total in HH:MM Format only.
I tried some thing like this but getting error 'Conversion failed when converting date and/or time from character string.':-
select CAST
(
(SUM (datepart(hh, convert (varchar, timespent, 108))) +
(sum(datepart(mi, convert (varchar, timespent, 108)))/60) ) AS VARCHAR(2)
)
+ ':' +
CAST
(
sum(datepart(mi, convert (varchar, timespent, 108))) - 60 * (sum(datepart(mi, convert (varchar, timespent, 108)))/60)
as VARCHAR(2)) from production

Query worked for me, I had just updated my table and decreased the size of TimeSpent to Varchar(25) from varchar(60) and it is fixed.
select CAST
(
(SUM (datepart(hh, convert (varchar, timespent, 108))) +
(sum(datepart(mi, convert (varchar, timespent, 108)))/60) ) AS VARCHAR(2)
)
+ ':' +
CAST
(
sum(datepart(mi, convert (varchar, timespent, 108))) - 60 * (sum(datepart(mi, convert (varchar, timespent, 108)))/60)
as VARCHAR(2))from production

Related

select first day of previous month from record in sql server

I have a table that has a column called StartDateTime that stores datetime values. I need a statement that will return the date of the first day in the previous month of the current record. So, if the stored date is 2006-06-17 08:23:42.000 the statement would return 2006-05-01 00:00:00.000 and importantly if the stored date is 2006-01-17 08:23:42.000 the statement would return 2005-11-1 00:00:00.000
If I could use DATEBYPARTS this seems like it would be simple, but unfortunately I can not.
I tried using
CAST(
CAST( Year([StartDateTime]) as varchar(4) )
+ '-' +
CAST( (Month([StartDateTime])-1) as varchar(2) )
+ '-' +
CAST( '1' as varchar(2) )
AS DATETIME )
but it errors on January 1st dates and gives error "The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value."
select dateadd(mm, datediff(mm, 0, StartDateTime) - 1, 0)
from <yourtable>
Or, as Aaron Bertrand suggested in comments, more clear way
select dateadd(month, datediff(month, 0, StartDateTime) - 1, 0)
from <yourtable>
SQL FIDDLE EXAMPLE

How to check date range in mssql for epoch datetime

in one of the table the date column values are like below
date
25052008112228
26052008062717
table name is transaction
i tried using the below query but its throwing error
select * from transaction where date between '2012-01-06' and '2012-06-30'
select * from transaction where date between '2012/01/06' and '2012/06/30'
give me a solution.
The problem is that the [date] column doesn't contain a date in a format that will be automatically converted to an appropriate datetime value - it doesn't even contain a supported format value. So you're left shredding the text using string operations:
declare #Transactions table (TDate char(14))
insert into #Transactions (TDate) values
('25052008112228'),
('26052008062717')
select CONVERT(datetime,
SUBSTRING(TDate,5,4) + '-' +
SUBSTRING(TDate,3,2) + '-' +
SUBSTRING(TDate,1,2) + 'T' +
SUBSTRING(TDate,9,2) + ':' +
SUBSTRING(TDate,11,2) + ':' +
SUBSTRING(TDate,13,2))
from
#Transactions
Results:
2008-05-25 11:22:28.000
2008-05-26 06:27:17.000
You could wrap the CONVERT/SUBSTRING operations into a UDF, if you need to perform this kind of conversion often. Of course, ideal would be to change the column definition to store a genuine datetime value - almost all datetime issues arise when people treat them as text.
(Note, I've renamed both the table and the column, since using reserved words is usually a bad idea)
Your query could be something like:
;with converted as (
select *,CONVERT(datetime,
SUBSTRING([Date],5,4) + '-' +
SUBSTRING([Date],3,2) + '-' +
SUBSTRING([Date],1,2) + 'T' +
SUBSTRING([Date],9,2) + ':' +
SUBSTRING([Date],11,2) + ':' +
SUBSTRING([Date],13,2)) as GenuineDate
from [Transaction]
)
select * from converted where GenuineDate between '20120106' and '20120630'
(Note that I've also changed the date literals in the final query to a safe format also)
-- asp time stamp
select * from [transaction] where
cast(SUBSTRING([date],5,4) + '-' + SUBSTRING([date],3,2) + '-' +
SUBSTRING([date],1,2) + ' ' + SUBSTRING([date],9,2) +
':' + SUBSTRING([date],11,2) + ':' +
SUBSTRING([date],13,2) as datetime)
between '2008-05-26' and '2012-01-06'
-- unix epoch time
select * from [transaction] where [date]
between DATEDIFF( SECOND, '01-01-1970 00:00:00', '2012-01-06' )
and DATEDIFF( SECOND, '01-01-1970 00:00:00', '2012-06-30')

How to format int to price format in SQL?

I select the price 1000000 and I need to format it to $1,000,000. How can I do that in SQL?
To format with commas, you can use CONVERT with a style of 1:
declare #money money = 1000000
select '$' + convert(varchar, #money, 1)
will produce $1,000,000.00
If you want to remove the last 3 characters:
select '$' + left(convert(varchar, #money, 1), charindex('.', convert(varchar, #money, 1)) - 1)
and if you want to round rather than truncate:
select '$' + left(convert(varchar, #money + $0.50, 1), charindex('.', convert(varchar, #money, 1)) - 1)
Creating Function:
CREATE FUNCTION [dbo].[f_FormatMoneyValue]
(
#MoneyValue money
)
RETURNS VARCHAR(50)
AS
BEGIN
RETURN cast(#MoneyValue as numeric(36,2))
END
Using in Select Query:
Select dbo.f_FormatMoneyValue(isnull(SalesPrice,0))SalesPrice from SalesOrder
Output:
100.00
Formatting Money Value with '$' sign:
CREATE FUNCTION [dbo].[f_FormatMoneyWithDollar]
(
#MoneyValue money
)
RETURNS VARCHAR(50)
AS
BEGIN
RETURN '$' + convert(varchar, #MoneyValue, 1)
END
Output:
$100.00
Note: The above sample is for the money field. You can modify this function according to your needs
Hope this helps you..! :D
SELECT FORMAT(price, 'C2', 'en-us')
The SQL Server money datatype is just decimal(10, 4). To my knowledge there is no datatype that will present the way you want.
Adding the dollar sign and commas is something that should belong in the application logic, but if you really must do it through a database object consider adding the dollar sign, and commas every three characters (after the decimal point). In other words, you'll have to convert the int to varchar and do string manipulation.
It depends, however, there's no simple way to do it in standard SQL specs(SQL-92, SQL-2003, etc.).
For PostgreSQL PL/pgSQL and Oracle PL/SQL, you can use to_char to format numbers:
select to_char(1234567.123, 'FM$999,999,999.99')
Which gives output:
$1,234,567.12
See: http://www.postgresql.org/docs/7/static/functions2976.htm

SQL Server: Computed Column with different datatypes

I am trying to get a field to display the combination of a a field with data type int and another as nvarchar under Computed Column Specification, but am getting the following error:
Conversion failed when converting the nvarchar value 'y' to data type int.
Computed Column Specification Forumula: [myNvarCharField] + ' ' + [myIntField]
Is it not possible to concatenate fields from different datatypes under the Computed Column Specification in SQL Server 2008?
Here is how you would use a string and an int as computed column math. Try this:
create table TestComputedCols
(
someint int not null,
somestring nvarchar(10) not null,
combination as (somestring + ' ' + cast(someint as nvarchar))
)
When you mix datatypes in an expression, implicit conversions happen according to "datatype precedence". Int is higher precedence than nvarchar so CAST the int first
...
MyComputedColumn AS [myNvarCharField] + ' ' + CAST([myIntField] AS nvarchar)
...

problem with convert text to time in sql server 2008?

i have this Ttime as nvarchar(10): "09:52:48" and i have TmpTime as date
and i try to convert like this: "UPDATE MEN SET TmpTime = CONVERT(DATETIME, Ttime ,108 )"
and i get in TmpTime this: "1900-01-01"
why ?
thank's in advance
If you also have a date field, you should to concatenate them before to cast:
CREATE TABLE #Sample ( DateField varchar(10), TimeField varchar(10) );
GO
INSERT INTO #Sample VALUES ('2009-01-24', '09:52:48');
SELECT CONVERT(DATETIME, DateField + ' ' + TimeField) as Converted FROM #Sample
And you'll get:
Converted
-----------------------
2009-01-24 09:52:48.000
You have a column defined as "date" and then you are sending only a time value into it
The date portion defaults to zero which is 01 January 1900 in SQL (in the CONVERT). Then the time is ignored for a date column.
What do you expect to happen?
(The same would happen whether or not you use CONVERT or not because the column is "date")