0

早上好,我正在尝试用一些数据绘制一个动态表,这个查询,绘制一个包含一天、一周和一些我想动态计算的数据的表。

这是我的查询

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

这个查询给我画了一张这样的表格。

d          |w     |info |
2013-09-09 | 36   | 2780|
2013-09-10 | 37   | 2780|
2013-09-11 | 37   | 2780|
2013-09-12 | 37   | 2780|
2013-09-13 | 37   | 2780|
2013-09-14 | 37   | 2780|
2013-09-15 | 37   | 2780|
2013-09-16 | 37   | 2780|

但是信息的列不是动态计算的,这是我的困境。

关键是 d 列是动态计算的,这就是我想在 info 的列查询中使用的值,就像这样,WHERE CONVERT(DATE, Solicitado, 102) = d) as info而不是WHERE CONVERT(DATE, Solicitado, 102) = '2013-10-11') as info其中 D 是每一行中的日期变化,我尝试它的方式只是给了我相同的的数据'2013-10-11'

在该子查询中更改一天之类的东西

谢谢

4

1 回答 1

0

基本方法是将生成日期的部分与计算该日期信息的部分分开:

;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

Example SQLFiddle

于 2013-11-02T16:07:57.940 回答