考虑到一个带有id列和int列的简单MySQL表,我需要计算 gap 等于或大于某个值的次数。
让我们说价值将是10。
给出以下样本记录:
{1, 2, 3} = 1 time
{1, 2, 3, 4, 5, 6, 7, 8, 9} = 1 time;
{1, 2, 3, 14, 17} = 2 times (1, 2, 3 and 14, 17);
{1, 2, 3, 14, 20, 40, 42} = 3 times (1, 2, 3 and 14, 20 and 40, 42);
是否可以使用mysql解决问题?
答案 0 :(得分:1)
是。对于列t
和id
的表num
,这将是这样的:
SET @n = 10;
SELECT 1 + SUM(COALESCE(t3.f, 0))
FROM (
SELECT DISTINCT t1.num, (
SELECT CASE WHEN t2.num - t1.num > @n THEN 1 ELSE 0 END
FROM t t2
WHERE t2.num > t1.num
ORDER BY num LIMIT 1
) AS f
FROM t t1
) t3