SQL Read different timeframes for a known period

How to count continuous time frames

My data is as follows:

Id| Em_Name|Em_Reg_Date
--------------------------------
1 | John   |2010-03-30 00:00:00  
1 | John   |2010-03-31 00:00:00  
2 | Marc   |2010-10-26 00:00:00  
2 | Marc   |2010-10-27 00:00:00  
2 | Marc   |2010-10-28 00:00:00  
2 | Marc   |2010-10-29 00:00:00  
2 | Marc   |2010-12-16 00:00:00  
2 | Marc   |2010-12-17 00:00:00    
2 | Marc   |2010-12-20 00:00:00  
2 | Marc   |2010-12-21 00:00:00  
2 | Marc   |2010-12-22 00:00:00  
3 | Paul   |2010-02-25 00:00:00  
3 | Paul   |2010-02-26 00:00:00  
3 | Paul   |2010-12-13 00:00:00  
3 | Paul   |2010-12-14 00:00:00  
3 | Paul   |2010-12-15 00:00:00  
--------------------------------

A time interval is a continuous period of time. for example, Paul has the following two (2) time frames

 FRAME 1 FROM 2010-02-25 00:00:00  to 2010-02-26 00:00:00  
 FRAME 2 FROM 2010-12-13 00:00:00  to 2010-12-15 00:00:00  

So, the result should be like this:

1 John   1  
2 Marc   3  
3 Paul   2  

Question: I need to calculate the time frame for each employee.

The problem here is that I need to isolate the ongoing time frames in order to count them. I even tried the ad cursor (it works, but I have to store the data in the temp table) And I want it to be in a β€œsimple” SQL statement Using max to find the start date only works for one frame. You cannot find the second / third frame with max.

Does anyone have any new fresh ideas?

+3
3

SQL Server 2005 +

select em_name, COUNT(distinct startdate)
from
(
    select *, startdate = em_reg_date - ROW_NUMBER() over (
        partition by em_name order by em_reg_date) +1
    from tbl
) X
group by Em_Name

Oracle, DB2 Row_Number(),

+2

ID, em_name, , .

, , - ... ​​ . - , .

, (ID, Em_Reg_Date), .

SELECT
  ID,
  COUNT(*)
FROM
  your_table [source]
WHERE
  NOT EXISTS (
              SELECT
                *
              FROM
                your_table
              WHERE
                Em_Reg_Date = [source].Em_Reg_Date + 1
                AND ID = [source].ID
             )
GROUP BY
  ID


, " ", - , .

SET DATEFIRST 1   -- This just ensures that Monday is counted as Day 1

SELECT
  ID,
  COUNT(*)
FROM
  your_table [source]
WHERE
  NOT EXISTS (
              SELECT
                *
              FROM
                your_table
              WHERE
                ID = [source].ID
                AND Em_Reg_Date <= [source].Em_Reg_Date + CASE WHEN DATEPART(weekday, [source].Em_Reg_Date) >= 5 THEN 8 - DATEPART(weekday, [source].Em_Reg_Date) ELSE 1 END
                AND Em_Reg_Date >  [source].Em_Reg_Date
             )
GROUP BY
  ID
+2
SELECT Id, Name, COUNT( Id )
FROM (
   SELECT Id, Name
   FROM  `<your_table_name>` 
   GROUP BY Name, MONTH( Em_Reg_Date )
   ) as X
GROUP BY Id

MySQL 5.0.7

+1

Source: https://habr.com/ru/post/1794712/


All Articles