第一个表 table1 logtime字段是datetime 类型 要统计 15年一月份除周末的数据 如下
SELECT * FROM table1
WHERE(logtimeBETWEEN CAST('2015-01-01 00:00:00' AS datetime) AND CAST('2015-01-31 23:59:59' AS datetime))
AND DATEPART(WEEKDAY,logtime)<6
现在第二个表 table2 logtime字段是varchar类型的 也要统计15年一月份除周末的数据
SELECT * FROM table2
WHERE(logtime BETWEEN CAST('20150117000000' AS datetime) AND CAST('20150118235959' AS datetime))
AND DATEPART(WEEKDAY,logtime)<6
由于表2 的logtime字段不是datetime类型的以上的语句行不通了,我要实现和表1一样的统计效果 如何写sql语句呢?
------解决思路----------------------
SELECT * FROM table2对于table2可以这么做
WHERE(logtime BETWEEN CAST('20150117000000' AS datetime) AND CAST('20150118235959' AS datetime))
AND DATEPART(WEEKDAY,LEFT(logtime,8))<6
------解决思路----------------------
--创建转换函数
Create Function F_VToD
(
@Str NVarchar(20)
)
Returns Varchar(50)
AS
Begin
Declare @Msg NVarchar(50)
Set @Msg = SUBSTRING(@Str,1,4) + N'-' + SUBSTRING(@Str,5,2) + N'-' + SUBSTRING(@Str,7,2) + N' '
+ SUBSTRING(@Str,9,2) + N':' + SUBSTRING(@Str,11,2) + N':' + SUBSTRING(@Str,13,2)
Return @Msg
End
--查询
SELECT * FROM table2
WHERE(dbo.F_VToD(logtime) BETWEEN CAST('2015-01-17 00:00:00' AS datetime) AND CAST('2015-01-18 23:59:59' AS datetime))
AND DATEPART(WEEKDAY,dbo.F_VToD(logtime))<6