Panel użytkownika
Nazwa użytkownika:
Hasło:
Nie masz jeszcze konta?

[MS SQL] Przecięcie dwóch zakresów dat w sekundach

Ostatnio zmodyfikowano 2022-01-19 13:53
Autor Wiadomość
DejaVu
Temat założony przez niniejszego użytkownika
[MS SQL] Przecięcie dwóch zakresów dat w sekundach
» 2022-01-19 13:53:22
Zapytanie, które zwraca przecięcie dwóch zakresów dat (ile sekund na siebie nachodzą zakresy):
 SELECT *, IIF(DATEDIFF(SECOND, IntersectStart, IntersectEnd) < 0, 0 , DATEDIFF(SECOND, IntersectStart, IntersectEnd)) AS IntersectInSeconds
 FROM (
   SELECT RowNo, FromA, ToA, FromB, ToB,
    IIF(FromA > FromB, FromA, FromB) AS IntersectStart,
    IIF(ToA < ToB, ToA, ToB) AS IntersectEnd
   FROM  (
    SELECT 1 AS RowNo, CAST('2021-01-01 10:00:00' AS DATETIME) AS FromA, CAST('2021-01-01 11:00:00' AS DATETIME) AS ToA, CAST('2021-01-01 10:30:00' AS DATETIME) AS FromB, CAST('2021-01-01 11:30:00' AS DATETIME) AS ToB
    UNION
    SELECT 2 AS RowNo, CAST('2021-01-01 10:00:00' AS DATETIME) AS FromA, CAST('2021-01-01 11:00:00' AS DATETIME) AS ToA, CAST('2021-01-01 09:30:00' AS DATETIME) AS FromB, CAST('2021-01-01 10:30:00' AS DATETIME) AS ToB
    UNION
    SELECT 3 AS RowNo, CAST('2021-01-01 10:00:00' AS DATETIME) AS FromA, CAST('2021-01-01 11:00:00' AS DATETIME) AS ToA, CAST('2021-01-01 08:30:00' AS DATETIME) AS FromB, CAST('2021-01-01 09:30:00' AS DATETIME) AS ToB
    UNION
    SELECT 4 AS RowNo, CAST('2021-01-01 10:00:00' AS DATETIME) AS FromA, CAST('2021-01-01 11:00:00' AS DATETIME) AS ToA, CAST('2021-01-01 11:30:00' AS DATETIME) AS FromB, CAST('2021-01-01 12:30:00' AS DATETIME) AS ToB
  ) AS Tmp
 ) AS Tmp2
ORDER BY RowNo
MS SQL Intersect two date/time range in seconds.
P-179214
« 1 »
  Strona 1 z 1