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

Gabungkan baris yang berdekatan dalam SQL?

Artikel ini memberikan beberapa kemungkinan solusi untuk pertanyaan Anda

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

Yang ini sepertinya yang paling lurus ke depan:

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. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Wawasan tentang Batasan Unik SQL Server

  2. Menghubungkan ke SQLServer 2005 dengan adodbapi

  3. Cara Menampilkan Kolasi Server di SQL Server (T-SQL)

  4. Bagaimana cara mengabaikan tag html di Sql Server 2008 Pencarian Teks Lengkap

  5. UNTUK XML PATH dan rangkaian string