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 の列クエリで使用したい値です。D がすべての行で変化する日付ではWHERE CONVERT(DATE, Solicitado, 102) = d) as infoなく、このようなものです。WHERE CONVERT(DATE, Solicitado, 102) = '2013-10-11') as infoのデータ'2013-10-11'

そのサブクエリで日を変更するWhileのようなもの

ありがとう

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 に答える