如何在最小和最大日期之间获得以下查询的所有内容

时间:2016-02-03 21:54:31

标签: sql sql-server

我在CheckPointTimeValue min和CheckPointTimeValue最大日期之间有这个查询,我希望将TimeValueBit显示为1,其他人显示为0.如何在SQL SERVER中执行此操作

SELECT C.CHECKPOINTNAME, TC.TERMINALCHECKPOINTID, CT.CheckPointTimeValue, CT.CheckPointTimeID, C.Scheduled, CT.ScheduledTimeValue
,CASE 
 WHEN CT.CheckPointTimeValue BETWEEN (SELECT MIN(CheckPointTimeValue) FROM  [TAMS].[CheckPointTimes]) AND (SELECT MAX(CheckPointTimeValue) FROM  [TAMS].[CheckPointTimes]) THEN 1
 ELSE 0
 END AS 'TimeValueBit'
 FROM [TAMS].[TerminalCheckPoints] TC
        INNER JOIN [TAMS].[CheckPoint] C ON C.CHECKPOINTID = TC.CHECKPOINTID
        LEFT JOIN [TAMS].[CheckPointTimes] CT ON CT.TerminalCheckPointID = TC.TERMINALCHECKPOINTID
        WHERE TC.TERMINALID = 1 AND TC.CHECKPOINTTYPE = 'TRUCK'
        ORDER BY C.SEQUENCENUMBER

enter image description here

1 个答案:

答案 0 :(得分:1)

;WITH cte AS (
    SELECT C.CHECKPOINTNAME, TC.TERMINALCHECKPOINTID, CT.CheckPointTimeValue, CT.CheckPointTimeID, C.Scheduled, CT.ScheduledTimeValue
    ,CASE 
       WHEN CT.CheckPointTimeValue BETWEEN (SELECT MIN(CheckPointTimeValue) FROM [TAMS].[CheckPointTimes]) AND (SELECT MAX(CheckPointTimeValue) FROM  [TAMS].[CheckPointTimes]) THEN 1
       ELSE 0
     END AS 'TimeValueBit'
    FROM [TAMS].[TerminalCheckPoints] TC
    INNER JOIN [TAMS].[CheckPoint] C ON C.CHECKPOINTID = TC.CHECKPOINTID
    LEFT JOIN [TAMS].[CheckPointTimes] CT ON CT.TerminalCheckPointID = TC.TERMINALCHECKPOINTID
    WHERE TC.TERMINALID = 1 AND TC.CHECKPOINTTYPE = 'TRUCK'
    ORDER BY C.SEQUENCENUMBER)

SELECT 
  CheckPointName
, TerminalCheckPointID
, CheckPointTimeValue
, CheckPointTimeID
, Scheduled
, ScheduledTimeValue
, CASE 
    WHEN TerminalCheckPointID BETWEEN (SELECT MIN(TerminalCheckPointID) FROM cte WHERE TimeValueBit = 1) AND (SELECT MAX(TerminalCheckPointID) FROM cte WHERE TimeValueBit = 1) 
      THEN 1  
      ELSE 0
    END AS TimeValueBit
FROM
 cte