在SQL中绘制动态表
早上好,我正在尝试用一些数据绘制一个动态表,这个查询,绘制一个表,其中有一天,他的一周,还有一些我想要动态计算的数据 这是我的问题在SQL中绘制动态表,sql,sql-server,dynamic,subquery,Sql,Sql Server,Dynamic,Subquery,早上好,我正在尝试用一些数据绘制一个动态表,这个查询,绘制一个表,其中有一天,他的一周,还有一些我想要动态计算的数据 这是我的问题 use Alfri ;with monthDates as ( select DATEADD(month, 0, CONVERT(DATE,'2013-09-09',102)) as d ,DATEPART(week, DATEADD(month, datediff(month, 0, '2013-09-09'),0)) as w
use Alfri
;with monthDates
as
(
select DATEADD(month, 0, CONVERT(DATE,'2013-09-09',102)) as d
,DATEPART(week, DATEADD(month, datediff(month, 0, '2013-09-09'),0)) as w,
(
SELECT SUM(
CASE WHEN arrive_yard IS NOT NULL THEN
DATEDIFF(mi, Solicitado, Libre)-DATEDIFF(mi, arrive_yard, leave_yard)
ELSE
DATEDIFF(mi, Solicitado, Libre)
END
) as Tiempo
FROM MovimientoHoras
WHERE CONVERT(DATE, Solicitado, 102) = '2013-10-11'
) as info
union all
select DATEADD(day, 1, d)
,DATEPART(week, DATEADD(day, 1, d))
, info
from monthDates
where d < DATEADD(month, datediff(month, 0, '2013-10-09')+1,-1)
)
SELECT * FROM monthDates
但是信息栏不是动态计算的,这是我的dilenma
重点是d列是动态计算的,这是我想在info的列查询中使用的值,类似于这样,其中CONVERTDATE,Learcado,102=d作为info,而不是其中CONVERTDATE,Learcado,102='2013-10-11'作为info,其中d是每行中更改的日期,我尝试的方式只是给了我相同的“2013-10-11”数据
在子查询中更改一天的时间
感谢基本方法是将生成日期的部分与计算该日期信息的部分分开:
;with monthDates as (
select
cast('20130909' as date) as d,
datepart(week, dateadd(month, datediff(month, 0, '2013-09-09'), 0)) as w
union all
select
dateadd(day, 1, d),
datepart(week, dateadd(day, 1, d))
from
monthDates
where
d < dateadd(month, datediff(month, 0, '2013-10-09') + 1, -1)
)
select
m.d,
m.w,
sum(
datediff(mi, Solicitado, Libre)
- case when arrive_yard is not null then
datediff(mi, arrive_yard, leave_yard)
else 0 end
) info
from
monthDates m
left outer join
MovimientoHoras h
on cast(Solicitado as date) = m.d
group by
m.d,
m.w
;with monthDates as (
select
cast('20130909' as date) as d,
datepart(week, dateadd(month, datediff(month, 0, '2013-09-09'), 0)) as w
union all
select
dateadd(day, 1, d),
datepart(week, dateadd(day, 1, d))
from
monthDates
where
d < dateadd(month, datediff(month, 0, '2013-10-09') + 1, -1)
)
select
m.d,
m.w,
sum(
datediff(mi, Solicitado, Libre)
- case when arrive_yard is not null then
datediff(mi, arrive_yard, leave_yard)
else 0 end
) info
from
monthDates m
left outer join
MovimientoHoras h
on cast(Solicitado as date) = m.d
group by
m.d,
m.w