要查詢連續出現多次的數據,可以使用窗口函數和分析函數來實現。以下是一個示例查詢來查找在一個表中連續出現超過3次的數據:
WITH consecutive_counts AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY data, grp ORDER BY id) AS rnk,
ROW_NUMBER() OVER (PARTITION BY data ORDER BY id) - ROW_NUMBER() OVER (PARTITION BY data, grp ORDER BY id) AS diff
FROM (
SELECT *,
ROW_NUMBER() OVER (ORDER BY id) - ROW_NUMBER() OVER (PARTITION BY data ORDER BY id) AS grp
FROM your_table
) t
)
SELECT data, COUNT(*) AS consecutive_count
FROM consecutive_counts
GROUP BY data, diff
HAVING COUNT(*) > 3
在這個例子中,首先使用ROW_NUMBER()來給每行數據分配一個唯一的序號,然后根據數據的變化情況(連續出現的數據在同一個grp組中)計算出連續出現次數,并最終根據這個次數來篩選出連續出現超過3次的數據。