Sum of datetime column in sql 05 - sql-server

I have a column named as "total_hours_worked" in my sql table which is of "datetime" datatype
I want to find out the total of "total hours worked in sql server".
How to do this?
I googled but didn't got a practical solution.

Something like this if I understand your data correctly.
declare #T table
(
total_hours_worked datetime
)
insert into #T values ('05:30:00')
insert into #T values ('10:00:00')
insert into #T values ('15:00:00')
select sum(datediff(minute, 0, total_hours_worked)) / 60.0 as hours_worked
from #T
Result:
hours_worked
---------------------------------------
30.500000
If you only need to store the hours you should consider an integer datatype instead of datetime. It will be more efficient and easier to deal with.

Try this.Here I considered seconds also.
declare #T table
(
total_hours_worked datetime
)
insert into #T values ('05:30:00')
insert into #T values ('10:00:00')
insert into #T values ('15:00:00')
insert into #T values ('05:25:45')
select SUM((DATEPART(hh,total_hours_worked)*60)+DATEPART(mi,total_hours_worked)+(DATEPART(ss,total_hours_worked)/(60.0)))/60.0 as TotalHours from #T

Related

Calculating statistics of interactions between football players

I have a table of kicks between a number of football players. Most interactions have both a kicker and receiver, but sometimes the pass is made but never received. The table contains 3 columns. For purposes of the example, I have added a "PassID" column to assist with the description of the problem.
The table looks as follows:
create table #T (Player1 varchar(25),Action varchar(25),Player2 varchar(25),PassID int)
insert into #T select 'Jamie','Kicked to','Pierre',1
insert into #T select 'Pierre','Received from ','Jamie',1
insert into #T select 'Jamie','Kicked to ','Mohamed',2
insert into #T select 'Jamie','Received from ','Kun',3
insert into #T select 'Kun ','Kicked to','Jamie',3
insert into #T select 'Mohamed','Received from ','Pierre',4
insert into #T select 'Pierre','Kicked to','Mohamed',4
insert into #T select 'Mohamed','Kicked to','Kun',5
insert into #T select 'Jamie ','Kicked to ','Kun',6
insert into #T select 'Kun ','Received from ','Jamie',6
insert into #T select 'Jamie','Received from ','Kun',7
insert into #T select 'Kun ','Kicked to','Jamie',7
I have to answer the following question using SQL server:
How many unique interactions exist, where a unique interaction is defined as a kick between two players, whether completed or not and where the direction of the interaction does not matter?
In this simple example, I know the answer is 5,being:
Jamie/Pierre
Jamie/Mohamed
Jamie/Kun
Mohamed/Pierre
Mohamed/Kun
How do I extract this answer from the table using T-SQL statement?
SELECT COUNT(DISTINCT CASE
WHEN Player1 > Player2 THEN CONCAT(Player1,'+',Player2)
ELSE CONCAT(Player2,'+',Player1)
END )
FROM #T
WHERE Action = 'Kicked To';
Here is a SQL Fiddle
Try with the below code.
Select CONCAT(x.Player1,'/',x.Player2)Title from (
Select *,ROW_NUMBER() over (PARTITION by passid order by passid)Row from #T
)X
where Row=1

Display few specific rows always at the top

I want to display a few specific Rows always at top of the query results.
For example: Cities Table. Columns: City ID, City Name
I want to fetch Query result where Mumbai, Bangalore, Chennai, Hyderabad should display at the top always.
1st way:
I can insert these records first in the table so that they will get displayed always at the top.
But, this way will not work if any other city gets added after a few months that I also want to display at the top.
Use an iif in your order by clause:
SELECT CityId, CityName
FROM Cities
ORDER BY IIF(CityName IN ('Mumbai', 'Bangalore', 'Chennai', 'Hyderabad'), 0, 1), CityName
You can't rely on the order in which you've entered the records to the table, because database tables are unsorted by nature, and without an order by clause, the order of the result set will be arbitrary.
For more information, read The “Natural order” misconception on my blog.
Try this:
Declare #t table (cityID int,cityname nvarchar(50))
insert into #t values (2,'Gujrat')
insert into #t values (4,'Surat')
insert into #t values (6,'Mumbai')
insert into #t values (3,'Bangalore')
insert into #t values (5,'Chennai')
insert into #t values (1,'Hyderabad')
select * from #t
order by case when cityname in ('Mumbai','Bangalore','Chennai','Hyderabad') then 0 else 1 END
Clean way of doing this,
Declare #t table (cityID int,cityname nvarchar(50))
Declare #DesireOrder table (id int identity,CityID int) -- instead of cityname
insert into #DesireOrder values (6),(3),(5),(1)
insert into #t values (2,'Gujrat')
insert into #t values (4,'Surat')
insert into #t values (6,'Mumbai')
insert into #t values (3,'Bangalore')
insert into #t values (5,'Chennai')
insert into #t values (1,'Hyderabad')
insert into #t values (8,'Delhi')
insert into #t values (7,'New Delhi')
select t.* from #t t
left join DesireOrder O on t.cityid=O.cityid
order by o.id,t.cityID
Main idea is #DesireOrder, rest you can implement as per your requirement.

Get inserted timestamp

in our T-SQL database We have some timestamp column, every time we insert or update a record we select the timestamp from the record the same key we inserted or updated.
We want avoid the double search: for update and for select, we tried something like this:
declare #table table(id int, val timestamp not null)
declare #table2 table(val timestamp)
insert #table(id)
output inserted.val into #table2
values (1)
but it does not compile, i have an error in Italian, something like 'a timestamp column can not be set explicitly'
any hint?
The problem is that TIMESTAMP is a data type that is automatically generated and only exposed as read-only. It's based around an incrementing number within the system.
SQL Server: Cannot insert an explicit value into a timestamp column
Try this:
DECLARE #table TABLE(id INT, val TIMESTAMP NOT NULL)
DECLARE #table2 TABLE(val DATETIME)
INSERT #table (id)
OUTPUT inserted.val INTO #table2(val)
VALUES (1)
SELECT
t.id,
t.val,
CONVERT( TIMESTAMP, t2.val ) AS table2_timestamp
FROM
#table AS t,
#table2 AS t2

How to compare datetime in SQL Server in where clause

I have CreatedDate as datetime column in my database table. I want to fetch the rows where CreatedDate and current time difference is more than 1 hour
Select * from TableName where (DateDiff(hh,CreatedDate,GetDate())>1
Answer by #Amit Singh works if you only care about the hour value itself, versus any 60 minute period.
The problem with using DATEDIFF(hh) that way is that times of 13:01 and 14:59 are only one "hour" apart.
Like:
select datediff(hh,'1/1/2001 13:59','1/1/2001 14:01')
I think doing this would address that issue:
declare #cd datetime='9/12/2013 03:10';
declare #t table(id int,CreatedDate datetime);
insert #t select 1,'9/12/2013 02:50';
insert #t select 2,'9/12/2013 02:05';
select * from #t where #cd>(DateAdd(hh,1,CreatedDate))
Dan Bellandi raises a valid point, but if it really matters if the dates should be 60 minutes apart, then just check if they are 60 minutes apart:
SELECT * FROM TableName WHERE DATEDIFF(MINUTE, DateColumnName, GETDATE()) >= 60
If you don't expect any rows created in the future...
where CreatedDate < dateadd(hour, -1, getdate())
CREATE TABLE trialforDate
(
id INT NULL,
NAME VARCHAR(20) NULL,
addeddate DATETIME NULL
)
INSERT INTO trialforDate VALUES (1,'xxxx',GETDATE())
INSERT INTO trialforDate VALUES (2,'yyyy',GETDATE())
INSERT INTO trialforDate VALUES (1,'zzzz','2013-09-12 11:20:40.533')
SELECT *
FROM trialforDate
WHERE GETDATE() > DATEADD(HOUR, 1, addeddate)
C# Code
DateTime param1= System.DateTime.Now;
DateTime param2= System.DateTime.Now.AddHours(1);
SQL Query:
SELECT * FROM TableName WHERE CreatedDate = param1 AND CreatedDate =param2;

T-SQL query with date range

I have a fairly weird 'bug' with a simple query, and I vaguely remember reading the reason for it somewhere a long time ago but would love someone to refresh my memory.
The table is a basic ID, Datetime table.
The query is:
select ID, Datetime from Table where Datetime <= '2010-03-31 23:59:59'
The problem is that the query results include results where the Datetime is '2010-04-01 00:00:00'. The next day. Which it shouldn't.
Anyone?
Cheers
Moo
Take a look at How Are Dates Stored In SQL Server? and How Does Between Work With Dates In SQL Server?
If that is a smalldatetime it has 1 minute precision so if rounds up, for datetime it is 300 miliseconds
example
DECLARE #d DATETIME
SELECT #d = '2001-12-31 23:59:59.999'
SELECT #d
2002-01-01 00:00:00.000
DECLARE #d DATETIME
SELECT #d = '2001-12-31 23:59:59.998'
SELECT #d
2001-12-31 23:59:59.997
Always use less than next day at midnight, in your case
< '20100401'
try doing it like:
select ID, Datetime from Table where Datetime < '2010-04-01'
I always floor the datetime and increment the day and just use "<" less than.
to floor a datetime to just the day use:
SELECT DATEADD(day,DATEDIFF(day,0, GETDATE() ),0)
you can easily increment a datetime by using addition:
SELECT GETDATE()+1
by using the '23:59:59' you can miss rows, try it out:
DECLARE #YourTable table (RowID int, DateOf datetime)
INSERT INTO #YourTable VALUES (1,'2010-03-31 10:00')
INSERT INTO #YourTable VALUES (2,'2010-03-31')
INSERT INTO #YourTable VALUES (3,'2010-03-31 23:59:59')
INSERT INTO #YourTable VALUES (4,'2010-03-31 23:59:59.887')
INSERT INTO #YourTable VALUES (5,'2010-04-01')
INSERT INTO #YourTable VALUES (6,'2010-04-01 10:00')
select * from #YourTable where DateOf <= '2010-03-31 23:59:59'
OUTPUT
RowID DateOf
----------- -----------------------
1 2010-03-31 10:00:00.000
2 2010-03-31 00:00:00.000
3 2010-03-31 23:59:59.000
(3 row(s) affected
this query is wrong, because it does not find the missed rowID=4 record.
if you try to fix this with:
select * from #YourTable where DateOf <= '2010-03-31 23:59:59.999'
then RowID=5 will be included as well, which is wrong.
It's very odd that you are seeing that; I don't know why. But I will suggest that you write the query this way instead:
select ID, Datetime from Table where Datetime < '2010-04-01'

Resources