sql >> Database teknologi >  >> RDS >> Sqlserver

Flet tilstødende rækker i SQL?

Denne artikel giver en hel del mulige løsninger på dit spørgsmål

http://www.sqlmag.com/blog/puzzled-by-t-sql-blog-15/tsql/solutions-to-packing-date-and-time-intervals-puzzle-136851

Denne virker som den mest ligetil:

WITH StartTimes AS
(
  SELECT DISTINCT username, starttime
  FROM dbo.Sessions AS S1
  WHERE NOT EXISTS
    (SELECT * FROM dbo.Sessions AS S2
     WHERE S2.username = S1.username
       AND S2.starttime < S1.starttime
       AND S2.endtime >= S1.starttime)
),
EndTimes AS
(
  SELECT DISTINCT username, endtime
  FROM dbo.Sessions AS S1
  WHERE NOT EXISTS
    (SELECT * FROM dbo.Sessions AS S2
     WHERE S2.username = S1.username
       AND S2.endtime > S1.endtime
       AND S2.starttime <= S1.endtime)
)
SELECT username, starttime,
  (SELECT MIN(endtime) FROM EndTimes AS E
   WHERE E.username = S.username
     AND endtime >= starttime) AS endtime
FROM StartTimes AS S;


  1. SQL Server PDF fuldtekstsøgning virker ikke på FileStream PDF-fil

  2. Mysql - Sådan afsluttes/forlader du lagret procedure

  3. Old Style Oracle Outer Join-syntaks - Hvorfor skal du finde (+) på højre side af lighedstegnet i en Left Outer join?

  4. Hvordan MySQL gør den matematiske beregning af floating point addition?