获取符合条件的行数

时间:2016-07-11 00:02:03

标签: sqlite

SQLITE3

任务:获取包含以下数据的数据集 - 查看说明BESIDE COLUMNS

SELECT DISTINCT DateTime(Rounded, 'unixepoch') AS RoundedDate, -- Rounded DateTime to the floor hour
            Count() AS Count, -- Count of items that registered within the above time
            CAST (avg(Speed) AS INT) AS AverageSpeed, -- Average table.Speed column data within the defined datetime
            Count() AS SpeederCount -- ?? WTF? [pseudo constraints: if Speed > Speedlimit then +1]
FROM RawSpeedLane AS sl
   INNER JOIN
   SpeedLaneSearchData AS slsd ON slsd.ParentId = sl.Id
   INNER JOIN
   Projects AS p ON p.ProjectId = sl.ProjectId
WHERE sl.ProjectId = 72
GROUP BY RoundedDate;

上面的SQL目前为我提供了我需要的所有数据, EXECPT 用于最后一列。

最后一列应该是传递特定条件的记录数。我成功做到这一点的唯一方法是建立一个子查询...酷?好吧,但问题是子查询需要4分钟才能运行,因为好吧......我对SQL很糟糕:P无论我尝试编写多少种不同的方法,它仍然需要永远。

这是漫长但有效的版本。

  SELECT DISTINCT RoundedDate,
                Count() AS Count,
                CAST (avg(Speed) AS INT) AS AverageSpeed,
                (
                    SELECT count() 
                      FROM RawSpeedLane AS slr
                     WHERE slr.ProjectId = 72 AND 
                           datetime( ( (strftime('%s', Start) - (strftime('%M', Start) * 60 + strftime('%S', Start) ) ) ), 'unixepoch') = sl.RoundedDate AND 
                           Speed > p.SpeedLimit
                )
                AS SpeederCount
  FROM SpeedLaneReportDataView AS sl
       INNER JOIN
       Projects AS p ON p.ProjectId = sl.ProjectId
 WHERE sl.ProjectId = 72
 GROUP BY RoundedDate;

我目前只是为最后一栏

尝试了这个
(select Count() where sl.Speed > p.SpeedLimit)

但正如预期的那样,我得到1和0我不知道该怎么做。非常感谢任何引导我走向正确方向的提示或帮助。

2 个答案:

答案 0 :(得分:2)

我不认为SQLite有IIF,但CASE有效。

这是对Backs答案的回复,但我还没有发表评论。

SwiftHTTP

答案 1 :(得分:0)

SUMIIF

SELECT DISTINCT DateTime(Rounded, 'unixepoch') AS RoundedDate, -- Rounded DateTime to the floor hour
            Count() AS Count, -- Count of items that registered within the above time
            CAST (avg(Speed) AS INT) AS AverageSpeed, -- Average table.Speed column data within the defined datetime
            SUM(IIF(Speed > SpeedLimit, 1, 0)) AS SpeederCount
FROM RawSpeedLane AS sl