2015-02-10 83 views
1

我有SQL表數據,我需要僅作爲我下面圖像高亮以過濾連續日期塊..的Sql分區

enter image description here

我需要爲該選定塊上的每一行添加自定義費率(此費率可以在輸出上顯示爲單獨的列)。如果超過6行被捕獲,則$ 200適用於該塊的每一列。它不到6,就是125美元。出來應該是這樣的 enter image description here

它應該按EmpID進行分組。 我需要使用MSSQL進行輸出。任何一個可以幫助我

這是我已經通過SQL視圖

ALTER view [dbo].[vw_Test2] AS 

SELECT 
     tbl2.ID as Tbl2ID, 
     tbl1.[EmpID], 
     tbl1.[ExpInDateTime] as Tbl1ExpDate, 
     tbl2.[ExpInDateTime] as Tbl2ExpDate, 
      case when(CONVERT(date,tbl1.[ActInDateTime]) = CONVERT(date, DATEADD(DAY,1,tbl2.[ExpInDateTime]))) then 
       1 
      else 0 
      end as Token 
from [dbo].[vw_Test] tbl1 join [dbo].[vw_Test] tbl2 
on tbl1.ID=(tbl2.ID+1) 
GO 

唯一的事情是做我必須做這個使用SQL視圖

+3

請給一些更多的信息,例如想要的結果,如輸入所示! – jarlh 2015-02-10 08:20:24

+0

我正在使用MSSQL – CodeMind 2015-02-10 08:33:58

+1

請參閱此鏈接http://stackoverflow.com/questions/20402089/detect-consecutive-dates-ranges-using-sql – DevelopmentIsMyPassion 2015-02-10 08:38:31

回答

1

請嘗試這是一個觀點:

ALTER VIEW [dbo].[vw_Test2] AS 
    WITH PreResult AS (
     SELECT p.Id,p.EmpID,p.[DateTime],CASE WHEN LEAD(p.diff)OVER(ORDER BY p.Id) > 1 OR LEAD(p.EmpID)OVER(ORDER BY p.Id)<>p.EmpID THEN 1 ELSE 0 END StartNewGroup 
     FROM (
      SELECT t.Id,t.EmpID,t.[DateTime], COALESCE(DATEDIFF(day,LAG(t.[DateTime])OVER(PARTITION BY t.EmpID ORDER BY t.Id),t.[DateTime]),1) [diff] 
      FROM [dbo].[vw_Test] t 
     ) p 
    ) 
    SELECT r.Id,r.EmpID,r.[DateTime] 
     ,CASE WHEN COUNT(*)OVER(PARTITION BY r.NewGroup ORDER BY r.NewGroup) >= 6 THEN 250 ELSE 125 END [Rate] 
    FROM (
     SELECT b.Id,b.EmpID,b.[DateTime],1+COALESCE((SELECT SUM(a.StartNewGroup) FROM PreResult a WHERE a.Id<b.Id),0) NewGroup 
     FROM PreResult b 
    ) r 
GO 

另外也查詢一起玩:

CREATE TABLE #Test (Id BIGINT IDENTITY(1,1),EmpID BIGINT, [DateTime] DATETIME) 

INSERT INTO #Test (EmpID,[DateTime]) VALUES (5,'20150106'),(5,'20150107'),(5,'20150109'), 
    (5,'20150110'),(5,'20150126'),(5,'20150127'), 
    (5,'20150128'),(5,'20150129'),(5,'20150130'), 
    (5,'20150131'),(10,'20121203'),(10,'20121204'), 
    (10,'20121205'),(10,'20121206'), 
    (10,'20121207'),(10,'20121208'),(10,'20121209') 

;WITH PreResult AS (
    SELECT p.Id,p.EmpID,p.[DateTime],CASE WHEN LEAD(p.diff)OVER(ORDER BY p.Id) > 1 OR LEAD(p.EmpID)OVER(ORDER BY p.Id)<>p.EmpID THEN 1 ELSE 0 END StartNewGroup 
    FROM (
     SELECT t.Id,t.EmpID,t.[DateTime], COALESCE(DATEDIFF(day,LAG(t.[DateTime])OVER(PARTITION BY t.EmpID ORDER BY t.Id),t.[DateTime]),1) [diff] 
     FROM #Test t 
    ) p 
) 
SELECT r.Id,r.EmpID,r.[DateTime] 
    ,CASE WHEN COUNT(*)OVER(PARTITION BY r.NewGroup ORDER BY r.NewGroup) >= 6 THEN 250 ELSE 125 END [Rate] 
FROM (
    SELECT b.Id,b.EmpID,b.[DateTime],1+COALESCE((SELECT SUM(a.StartNewGroup) FROM PreResult a WHERE a.Id<b.Id),0) NewGroup 
    FROM PreResult b 
) r 

DROP TABLE #Test 

如果您有任何問題,請讓我知道。