It was one of those rare off days in office when the mailboxes and chat windows were taking place of the .Net IE in my desktop, and my TL thought of giving some job rather than idling out. His requirement was simple at first look but took little more time than expected.
There was a SQL table, Temperature, having two fields , Temp And Date.
------------------------
Date Temp
------------------------
10/1/2006 25
10/2/2006 27
10/3/2006 24
10/4/2006 28
10/5/2006 22
His requirement was that he needs a query that would present as output as
---------------------------------------------
Date Temp
---------------------------------------------
10/1/2006 - 10/2/2006 2
10/2/2006 - 10/3/2006 -3
10/3/2006 - 10/4/2006 4
10/4/2006 - 10/5/2006 -6
It did take some time to get working on this and finally made this query using temporary tables.
------------------
drop table #myTempTable1
drop table #myTempTable2
drop table #myTempTable3
SELECT
[date] AS date,
[temp] AS temp
INTO #myTempTable1
FROM Temperature
SELECT [date] AS Date,
[temp] AS Temp
INTO #myTempTable2
FROM Temperature
Create table #myTempTable3
(
[date] varchar(100),
[temp] int
)
declare @count1 int
declare @count2 int
set @count1 = (select count(*) from #myTempTable1)
set @count2 = (select count(*) from #myTempTable1) - 1
delete from #myTempTable2 Where [date] = (select top 1 [date] from #myTempTable2)
while(@count1>=0 or @count2>=0)
begin
insert into #myTempTable3 ( date,temp)
select top 1
(
Convert(varchar, (select top 1 date from #myTempTable1) )
+ ' - ' +
Convert(varchar, (select top 1 date from #myTempTable2))
) as [Date],
(
(select top 1 temp from #myTempTable2)-(select top 1 temp from #myTempTable1)
) as [Temp]
From #myTempTable1 , #myTempTable2
set @count1 = @count1 - 1
set @count2 = @count2 - 1
delete from #myTempTable1 Where [date] = (select top 1 [date] from #myTempTable1)
delete from #myTempTable2 Where [date] = (select top 1 [date] from #myTempTable2)
end
Select * from #myTempTable3
Friday, October 13, 2006
Sql Time
Category
Sql Server