Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

SQL Server - jumlah kumulatif pada data yang tumpang tindih - mendapatkan tanggal jumlah tersebut mencapai nilai yang diberikan

Lihat SQL Fiddle di sini .

with tbl as (
  -- this will generate daily merged ovelaping time
  select distinct
    a.id
    ,(
        select min(x.starttime) 
        from act x 
        where x.id=a.id and ( x.starttime between a.starttime and a.endtime
          or a.starttime between x.starttime and x.endtime )
    ) start1
    ,(
        select max(x.endtime) 
        from act x 
        where x.id=a.id and ( x.endtime between a.starttime and a.endtime
          or a.endtime between x.starttime and x.endtime )
    ) end1
  from act a

), tbl2 as 
(
  -- this will add minute and total minute column
  select 
    * 
    ,datediff(mi,t.start1,t.end1) mi
    ,(select sum(datediff(mi,x.start1,x.end1)) from tbl x where x.id=t.id and x.end1<=t.end1) totalmi
  from tbl t
), tbl3 as 
(
  -- now final query showing starttime and endtime for 5 hours other wise null in case not completed 5(300 minutes) hours
  select 
    t.id
    ,min(t.start1) starttime
    ,min(case when t.totalmi>300 then t.end1 else null end) endtime
  from tbl2 t
  group by t.id
)
-- final result 
select *
from tbl3
where endtime is not null


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Perhatian pengguna yang menjalankan SQL Server 2008 dan SQL Server 2008 R2

  2. bagaimana cara mengekstrak hanya tahun dari tanggal di sql server 2008?

  3. Bagaimana ekspresi CASE ini mencapai klausa ELSE?

  4. 6 Fungsi untuk Mendapatkan Hari, Bulan, dan Tahun dari Tanggal di SQL Server

  5. Menerapkan Penanganan Kesalahan dan Transaksi di SQL Server