如何在SQL Server中使值大于10的条件

时间:2012-03-01 04:15:49

标签: sql-server count

我遇到了过滤数据库的问题。这是我的表结构(并非所有也通过SQL命令过滤的值):

SELECT vehicleID,PositionDate,Speedreport 
FROM [PositionData820901-D] 
WHERE vehicleID = 'LT130' 
     AND (PositionDate between '20120214 00:00:00.000' AND '20120215 00:00:00.000' ) 
     AND (Speedreport BETWEEN 'Idle' and 'Moving')
ORDER BY positiondate

示例数据:

VehicleID   PositionDate                SpeedReport 
  LT130      2012-02-14 10:00:42.000      Moving 
  LT130      2012-02-14 10:01:42.000      Idle 
  LT130      2012-02-14 10:02:42.000      Moving 
  LT130      2012-02-14 10:03:42.000      Idle 
  LT130      2012-02-14 10:04:42.000      Idle 
  LT130      2012-02-14 10:05:42.000      Idle
  LT130      2012-02-14 10:06:42.000      Idle
  LT130      2012-02-14 10:07:41.000      Idle
  LT130      2012-02-14 10:08:41.000      Idle
  LT130      2012-02-14 10:09:41.000      Idle
  LT130      2012-02-14 10:10:41.000      Idle
  LT130      2012-02-14 10:11:41.000      Idle
  LT130      2012-02-14 10:12:41.000      Idle
  LT130      2012-02-14 10:13:40.000      Idle
  LT130      2012-02-14 10:14:40.000      Idle
  LT130      2012-02-14 10:15:40.000      Idle
  LT130      2012-02-14 10:16:40.000      Idle
  LT130      2012-02-14 10:17:40.000      Idle
  LT130      2012-02-14 10:18:40.000      Idle
  LT130      2012-02-14 10:19:39.000      Idle
  LT130      2012-02-14 10:20:39.000      Idle
  LT130      2012-02-14 10:21:39.000      Idle
  LT130      2012-02-14 10:22:39.000      Idle
  LT130      2012-02-14 10:23:39.000      Idle
  LT130      2012-02-14 10:24:39.000      Idle
  LT130      2012-02-14 10:25:38.000      Idle
  LT130      2012-02-14 10:26:38.000      Idle
  LT130      2012-02-14 10:27:38.000      Idle
  LT130      2012-02-14 10:28:38.000      Idle
  LT130      2012-02-14 10:29:38.000      Moving

现在我想返回以“空闲”值开头和结尾的行,这些值满足条件= count() > 10,但Idle值也必须在顺序行中,而不是在“移动”值或任何值之间别的..我想要的输出:

VehicleID  PositionDate               SpeedReport
   LT130    2012-02-14 10:03:42.000     Idle
   LT130    2012-02-14 10:28:38.000     Idle 

很抱歉长桌我尝试使用count(*) > 10,但没有提供我想要的输出。我希望有人能帮助我,我将非常感谢你的帮助。

1 个答案:

答案 0 :(得分:1)

我用Google搜索使用排名函数对连续行进行分组,然后找到this。以下是您的方案的代码:

;WITH groups AS 
(
SELECT VehicleID 
    , SpeedReport
    , PositionDate
    , row_number() OVER(ORDER BY PositionDate) 
       - row_number() OVER(PARTITION BY SpeedReport ORDER BY SpeedReport, PositionDate)
       AS groupid
FROM [PositionData820901-D]
WHERE vehicleID = 'LT130' 
   AND PositionDate between '20120214 00:00:00.000' AND '20120215 00:00:00.000' 
   AND Speedreport IN ('Idle', 'Moving')
)

SELECT VehicleID, SpeedReport, MIN(PositionDate) AS PositionDate
FROM groups
GROUP BY VehicleID, SpeedReport, groupid
HAVING COUNT(1) > 10
UNION
SELECT VehicleID, SpeedReport, MAX(PositionDate) AS PositionDate
FROM groups
GROUP BY VehicleID, SpeedReport, groupid
HAVING COUNT(1) > 10
ORDER BY PositionDate