我在将nvarchar转换为int时遇到了一些麻烦。
我想要做的是获得列的最长和最短时间,然后计算AVG时间,但列是nvarchar。
答案 0 :(得分:0)
Set Nocount On;
If Object_Id('tempdb.dbo.#sometable') Is Not Null
Begin
Drop Table #sometable;
End
If Object_Id('tempdb.dbo.#computetable') Is Not Null
Begin
Drop Table #computetable;
End
Create Table #sometable
(
RowId Int Identity(1,1) Primary Key
,TimeTaken Nvarchar(8)
)
Create Table #computetable
(
RowId Int Primary Key
,ComputeTime Int
)
Insert Into #sometable(TimeTaken) Values
('15:24:58'),('5:20:08'),('10:14:50'),('21:02:01'),('4:27:30'),('16:21:45')
Insert Into #computetable(RowId,ComputeTime)
Select st.RowId
,(st.HoursToSeconds + st.MinutesToSeconds + st.Seconds) As ComputeTime
From (
Select st.RowId
,(st.Hours * 3600) As HoursToSeconds
,(Cast(Left(st.TimeTaken, (Charindex(':', st.TimeTaken, 0) - 1)) As Int) * 60) As MinutesToSeconds
,Cast(Right(st.TimeTaken, (Charindex(':', st.TimeTaken, 0) - 1)) As Int) As Seconds
From (
Select st.RowId
,Cast(Left(st.TimeTaken, (Charindex(':', st.TimeTaken, 0) - 1)) As Int) As Hours
,Substring(st.TimeTaken, (Charindex(':', st.TimeTaken, 0) + 1), Len(st.TimeTaken)) As TimeTaken
From #sometable As st With (Nolock)
) As st
) As st
Select Max(ct.ComputeTime) As HighestTime
,Min(ct.ComputeTime) As LowestTime
,Avg(ct.ComputeTime) As AvgTime
From #computetable As ct With (Nolock)