Using PIVOT on Dates in One Column

Suppose you have a table that contains Job ID, when it was started, and when the Job ended. Now you want the difference in days between when it was started and when it ended. You can use the PIVOT command in SQL. From there you can then derive the difference in days, hours, minutes or any combination.


CREATE TABLE #Temp(
 NotesID int,
 Jobid int,
 Notes varchar(150),
 Dates datetime
 )

 Insert into #Temp Values (1,1,'Job Started','01/10/2013')
 Insert into #Temp Values (2,1,'Job Ended','05/10/2013')
 Insert into #Temp Values (3,2,'Job Started','02/10/2013')
 Insert into #Temp Values (4,2,'Job Ended','03/10/2013')
 Insert into #Temp Values (5,3,'Job Started','04/10/2013')
 Insert into #Temp Values (6,3,'Job Ended','05/10/2013')
 Insert into #Temp Values (7,4,'Job Started','05/10/2013')
 Insert into #Temp Values (8,4,'Job Ended','06/10/2013')
 Insert into #Temp Values (9,1,'Job Started','06/10/2013')
 Insert into #Temp Values (10,1,'Job Ended','06/10/2013')

Select *, datediff(day,[Job Started],[Job Ended]) as difference from (
   Select * from
    (
       Select jobid,Notes,Dates from Temp
    ) x
    pivot
    (
    min(Dates)
    for Notes in ([Job Started],[Job Ended])
  ) p
) ee

Drop table #temp

You can look at here as well.

Looking for quality web hosting? Look no further than Arvixe Web Hosting!

Tags: , , , , , , , , , , , , , , , | Posted under Programming/Coding | RSS 2.0

Author Spotlight

David Bauernschmidt

David Bauernschmidt

I live in the historical triangle of Virginia where I am married with two daughters. I have spent over 13 years working for a Fortune 500 company in the computer area. I started in VB 6.0 and by the time I ended my employment I was supervising a development team where we built many web applications. When my first daughter was born I wanted to spend more time with her so I left and became a programmer analyst for local government as well as launch my own company. Since then I have grown James River Webs into a profitable web design and application company helping small businesses create a big presence on the internet. As an employee I have created web application used by citizens and other companies. I enjoy fly fishing, and spending time with my family. I also enjoy learning new approaches and development tools when it comes to developing applications.

Leave a Reply

Your email address will not be published. Required fields are marked *


8 − 8 =

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>