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

Implementasi cte yang diperlukan untuk data hierarkis

Anda dapat melakukan ROW_NUMBER() dengan PARTITION BY dan kemudian lakukan self join dengan rn =rn + 1 dan lakukan DATEDIFF berdasarkan mana Anda dapat mengelompokkan hasil Anda.

Coba sesuatu seperti ini

DECLARE @Rules TABLE(RuleId  INT,Name CHAR(3),    StartDate DATE,           EndDate DATE)

INSERT INTO @Rules VALUES
(3 ,'TP3', '3/18/2015', '11/28/2015'),
(3 ,'TP3', '11/28/2015', '4/30/2016'),
(3 ,'TP3', '4/30/2016', '10/5/2016'),
(3 ,'TP3', '10/25/2016', '11/15/2016'),
(3 ,'TP3', '11/15/2016', null) 


;WITH CTE AS 
(
SELECT ROW_NUMBER() OVER(PARTITION BY RuleID ORDER BY StartDate) rn,*
FROM @Rules
), CTE2 AS
(
SELECT ISNULL(DATEDIFF(day,C1.EndDate,C2.StartDate),0) diff,C1.*
FROM CTE C1 
LEFT JOIN CTE C2 ON C1.rn + 1 = C2.rn
 AND C1.RuleId = C2.RuleId
)
SELECT RuleId,Name,MIN(StartDate)  StartDate,NULLIF(MAX(CASE WHEN EndDate IS NULL THEN '2999/12/31' ELSE EndDate END),'2999/12/31') EndDate
FROM
(
SELECT C2.Diff,C1.RuleId,C1.Name,C1.StartDate,C1.EndDate
FROM CTE2 C1
CROSS APPLY (SELECT ISNULL(SUM(Diff),0) Diff FROM CTE2 C2 WHERE C1.StartDate > C2.StartDate AND C1.RuleId = C2.RuleId) C2
) C
GROUP BY RuleId,Name,Diff
ORDER BY RuleId,Diff



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Transaksi Terdistribusi pada Server Tertaut antara sql server dan mysql

  2. Masalah Intellisense SQL Server 2008

  3. Koma dalam Data CSV

  4. Prosedur Tersimpan mengembalikan beberapa set hasil

  5. Tingkatkan penyetelan kinerja SQL Server dengan 3 tips ini