选择带有CTE的表格

时间:2016-09-05 15:29:30

标签: tsql sql-server-2012

我正在使用SQL Management Studio 2012,我想在表格中选择以下代码,但在使用CTE时从未这样做过。

With UniqueService AS (

SELECT 

  CASE WHEN LAG(ScheduleOfServiceID,1) OVER (ORDER BY ScheduleOfServiceID ASC, ActualHoursPerWeek ASC) = ScheduleOfServiceID
     THEN 0
     ELSE 1
     END AS UniqueService

  ,[ClientID]
  ,[ClientName]
  ,[ScheduleOfServiceID]
  ,[ActualHoursPerWeek]
  ,[ServicePlannedStartDate]
  ,[ServicePlannedEndDate]
  ,[ServiceActualStartDate]
  ,[ServiceActualEndDate]
  ,[ServiceProvided]
  ,[ServiceProvider]
  ,[AllocatedWorkerTeam]
  ,[StartDateFormatted]
  ,[SOSStartYearMonth]
  ,[EndDateFormatted]
  ,[SOSEndYearMonth]
  ,[ServicePlacementStartReason]
  ,[RecordToBeExcluded]
  ,CASE WHEN EndDateFormatted IN ('')
        AND ServiceActualEndDate IS NULL
        AND ServicePlannedEndDate IS NULL
        THEN NULL 
        WHEN EndDateFormatted IS NULL
        THEN ServiceActualEndDate
        WHEN EndDateFormatted IS NULL
        AND ServiceActualEndDate IS NULL
        THEN ServicePlannedEndDate
        ELSE EndDateFormatted
    END AS MasterEndDate


FROM [BIPROJECT].[adults].[tAllAdultsDomiciliaryCareReporting]

WHERE RecordToBeExcluded != 1


)

SELECT *,
     CASE WHEN ServicePlannedStartDate BETWEEN '2016-04-01' AND '2016-08-31' 
          AND  (MasterEndDate IS NULL
          OR MasterEndDate > '2016/08/31')
          THEN 1
          ELSE 0
     END AS ServiceStarted,

     CASE WHEN MasterEndDate BETWEEN '2016-04-01' AND '2016-08-31' 
          AND ServicePlannedStartDate NOT BETWEEN '2016-04-01' AND '2016-08-31' 
          THEN 1
          ELSE 0
     END AS ServiceEnded,

    CASE WHEN ServicePlannedStartDate BETWEEN '2016-04-01' AND '2016-08-31' 
          AND MasterEndDate BETWEEN '2016-04-01' AND '2016-08-31' 
          THEN 1
          ELSE 0
     END AS ServiceStartedAndEnded

FROM UniqueService

WHERE UniqueService = 1
        AND (ServiceActualStartDate BETWEEN '2016-04-01' AND '2016-08-31' 
        OR MasterEndDate BETWEEN '2016-04-01' AND '2016-08-31')

ORDER BY ClientID ASC, ScheduleOfServiceID ASC

我有一个快速的谷歌,并查看了其他一些堆栈帖子,但尚未取得任何成功。

0 个答案:

没有答案