日期:2014-05-18  浏览次数:20526 次

菜鸟求下SQL
SQL code

select zt_userinfo.[user_name],count(1) as s
,sum(case when datediff(mi,zt_flow_log.c_time,zt_flow_log.p_time) <10 then 1 else 0 end) as q
,sum(case when datediff(mi,zt_flow_log.c_time,zt_flow_log.p_time) <10 then 0 else 1 end) as d
from zt_userinfo,zt_flow_log
where zt_userinfo.login_name = zt_flow_log.p_task_user
group by zt_userinfo.[user_name]
得到的数据大概是这样:
user_name s q d
名1       4 3 1
名2       9 4 5
名3       7 3 4
得到s(总计),q(在10分钟内的为合格),d(10分钟外为不合格的)

现在想得到某个时间段的数据 如:c_time>'2000-1-1' and p_time<'2021-1-1'(时间为变量)

现在我要做成视图来操作  我该怎么改 



------解决方案--------------------
视图没有参数的

------解决方案--------------------
视图不带参数,做成存储过程不行么?
------解决方案--------------------
视图是不能接收参数的。
你可以把你的SQL 作为一个视图
查询的时候加时间条件
类似这样
SQL code

create view view_name
as
select zt_userinfo.[user_name],count(1) as s
,sum(case when datediff(mi,zt_flow_log.c_time,zt_flow_log.p_time) <10 then 1 else 0 end) as q
,sum(case when datediff(mi,zt_flow_log.c_time,zt_flow_log.p_time) <10 then 0 else 1 end) as d
,zt_flow_log.p_time
from zt_userinfo,zt_flow_log
where zt_userinfo.login_name = zt_flow_log.p_task_user
group by zt_userinfo.[user_name]
---查询时:
select user_name,s,q,d from view_name where p_time>'2000-1-1' and p_time<'2021-1-1'

------解决方案--------------------
视图条件都写死的吧?....

做个过程或函数吧...
------解决方案--------------------
SQL code

CREATE VIEW [dbo].[VW_VIEW1]
AS
select [user_name],c_time,p_time
from zt_userinfo,zt_flow_log
where zt_userinfo.login_name = zt_flow_log.p_task_user

GO

select [user_name],count(1) as s
,sum(case when datediff(mi,c_time,p_time) <10 then 1 else 0 end) as q
,sum(case when datediff(mi,c_time,p_time) <10 then 0 else 1 end) as d
from dbo.VW_VIEW1
group by [user_name]

------解决方案--------------------
SQL code

--动态拼接语句执行,你可以给这个语句封装成存储过程

declare @str varchar(max)
declare @date1 datetime
declare @date2 datetime
set @date1='2000-1-1'
set @date2='2021-1-1'
set @str='
if object_id('+'''v_test'''+') is not null
drop view v_test
go
create view v_test
as
select zt_userinfo.[user_name],count(1) as s
,sum(case when datediff(mi,zt_flow_log.c_time,zt_flow_log.p_time) <10 then 1 else 0 end) as q
,sum(case when datediff(mi,zt_flow_log.c_time,zt_flow_log.p_time) <10 then 0 else 1 end) as d
from zt_userinfo,zt_flow_log
where zt_userinfo.login_name = zt_flow_log.p_task_user
and c_time>'+''''+CONVERT(varchar(10),@date1,120)+''''+'
 and p_time<'+''''+CONVERT(varchar(10),@date2,120)+''''+'
group by zt_userinfo.[user_name]
go
'
print @str

/*

if object_id('v_test') is not null
drop view v_test
go
create view v_test
as
select zt_userinfo.[user_name],count(1) as s
,sum(case when datediff(mi,zt_flow_log.c_time,zt_flow_log.p_time) <10 then 1 else 0 end) as q
,sum(case when datediff(mi,zt_flow_log.c_time,zt_flow_log.p_time) <10 then 0 else 1 end) as d
from zt_userinfo,zt_flow_log
where zt_userinfo.login_name = zt_flow_log.p_task_user
and c_time>'2000-01-01'
 and p_time<'2021-01-01'
group by zt_userinfo.[user_name]
go
*/