sql - 计算sqlite中的相邻记录数

标签 sql sqlite

我有下表

ID  location date
--  -------- -----
01  loc#1    10-06-2014
05  loc#1    11-06-2014
06  loc#2    13-06-2014
08  loc#2    14-06-2014
10  loc#2    15-06-2014
14  loc#1    16-06-2014
17  loc#1    17-06-2014
20  loc#1    18-06-2014

我需要的是获取每个位置以及按 ID 排序提到该位置的相邻记录的数量

location count(location)
-------- --------------- 
loc#1    2 
loc#2    3 
loc#1    3

使用 count + group by 的问题在于,它会计算同一位置的所有记录,而不仅仅是相邻的记录,并输出一组唯一的位置

select location, count(location) from table group by location order by ID

location count(location)
-------- --------------- 
loc#1    5
loc#2    3

知道如何获得正确的查询吗?因为我不想以编程方式制作它,因为我正在 iPhone 上处理数千条记录,这会产生性能问题

最佳答案

select minAdjLoc.ID, max(minAdjLoc.location) 'Loc', count(distinct adjLocs.ID) 'Count' 
from test minAdjLoc              -- Minimum record in each adjacent group
inner join test adjLocs          -- All adjacent record, including self
    on adjLocs.location = minAdjLoc.location
    and adjLocs.ID >= minAdjLoc.ID
left join test intruder          -- Possible intruder with different location
    on intruder.location <> minAdjLoc.location
    and intruder.ID > minAdjLoc.ID
    and intruder.ID < adjLocs.ID
left join test lowerThanMin      -- Possible record lower than minAdjLoc
    on lowerThanMin.ID < minAdjLoc.ID
    and lowerThanMin.location <> minAdjLoc.location
left join test lowerIntruder
    on (lowerThanMin.ID is null or lowerThanMin.ID < lowerIntruder.ID)
    and lowerIntruder.ID < minAdjLoc.ID
    and lowerIntruder.location = minAdjLoc.location
    where intruder.ID is null    -- There can't be any record with a different location inside the group
    and lowerIntruder.ID is null -- Ensure minAdjLoc is in fact the record with minimum ID
group by minAdjLoc.ID            --The minimum ID of the adjacent group is unique
order by minAdjLoc.ID

关于sql - 计算sqlite中的相邻记录数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24405113/

相关文章:

java - osql -S 没有给我预期的结果

SQL 等效于 c# 中的 Math.Floor()

database - 有没有办法查询特定表或列在 sqlite 中存储了多少数据?

sqlite - 在SQLite中实现/使用外键?

php - 我如何使用 LEFT JOIN mysql 从另一个表派生 count(*)

sql - 如何在可能具有空值的字段上创建唯一索引 (Oracle 11g)?

sql - 以正确的方式为 Windows 构建 sqlite

SQLite NOT IN 查询很慢

android - 使用 delete 时出现空指针异常

java - 崩溃到主 Activity 屏幕