sql >> データベース >  >> RDS >> Sqlserver

SQL:複数の行にまたがる連続した日付範囲を見つけますか?

    サンプルデータ

    create table tbl (person int, startdate datetime, enddate datetime, hours decimal(10,2));
    insert tbl values
    (5163 ,'2013-04-29 07:00:00.000' ,'2013-04-29 11:00:00.000', 4.00),
    (5163 ,'2013-04-29 11:30:00.000' ,'2013-04-29 15:30:00.000', 4.00),
    (5163 ,'2013-04-29 15:30:00.000' ,'2013-04-29 19:06:00.000', 3.60),
    (5851 ,'2013-05-02 19:00:00.000' ,'2013-05-02 23:00:00.000', 4.00),
    (5851 ,'2013-05-02 23:00:00.000' ,'2013-05-03 00:00:00.000', 1.00),
    (5851 ,'2013-05-03 00:00:00.000' ,'2013-05-03 00:31:00.000', 0.52);
    

    クエリ

    ;with cte as (
        select person, startdate, enddate, hours
        from tbl
        union all
        select t.person, cte.startdate, t.enddate, cast(cte.hours + t.hours as decimal(10,2))
        from cte
        join tbl t on cte.person = t.person and cte.enddate = t.startdate
    ), cte2 as (
        select *, rn = row_number() over (partition by person, enddate order by startdate)
        from cte
    )
    select person, startdate, max(enddate) enddate, max(hours) hours
    from cte2
    where rn=1
    group by person, startdate
    order by person, startdate;
    

    結果

    person      startdate               enddate                 hours
    ----------- ----------------------- ----------------------- -------
    5163        2013-04-29 07:00:00.000 2013-04-29 11:00:00.000 4.00
    5163        2013-04-29 11:30:00.000 2013-04-29 19:06:00.000 7.60
    5851        2013-05-02 19:00:00.000 2013-05-03 00:31:00.000 5.52
    



    1. SQLステートメントで変数名を使用するにはどうすればよいですか?

    2. Zend Db/Mysql-Selectで挿入

    3. Rails:rake db:create:all(サーバーに接続できませんでした)

    4. PLS-00201:識別子'R_CUR'は動的SQLで宣言する必要があります