抱歉,起初我不明白关于 SQLFiddle 的评论。我在那里测试了代码,发现我需要修复更多的东西。
查询需要将 n* 列从最终的 group-by 表达式移动到聚合,以及 ( 在第一个 FROM 和第二个 SELECT 之间。 - 并且 COUNT( ) >= 2 而不是 COUNT( ) > 2。
现在,在您的测试代码上运行时,它可以工作了。
这是测试的 URL http://sqlfiddle.com/#!2/9e3cb/21/0
更正答案:
SELECT id, MAX(n1) n1, MAX(n2) n2, MAX(n3) n3, MAX(n4) n4, MAX(n5) n5,
MAX(n6) n6, MAX(n7) n7, MAX(n8) n8, MAX(n9) n9, MAX(n10) n10,
MAX(GrpSize) Max, COUNT(GrpNumber) Sets
FROM (
SELECT id, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, GrpNumber, COUNT(*) GrpSize
FROM (
SELECT id, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10,
CASE Numbers.N
WHEN 1 THEN n1 - N
WHEN 2 THEN n2 - N
WHEN 3 THEN n3 - N
WHEN 4 THEN n4 - N
WHEN 5 THEN n5 - N
WHEN 6 THEN n6 - N
WHEN 7 THEN n7 - N
WHEN 8 THEN n8 - N
WHEN 9 THEN n9 - N
WHEN 10 THEN n10 - N
END GrpNumber
FROM `mytbl`
CROSS JOIN (
SELECT 1 AS N UNION ALL
SELECT 2 AS N UNION ALL
SELECT 3 AS N UNION ALL
SELECT 4 AS N UNION ALL
SELECT 5 AS N UNION ALL
SELECT 6 AS N UNION ALL
SELECT 7 AS N UNION ALL
SELECT 8 AS N UNION ALL
SELECT 9 AS N UNION ALL
SELECT 10 AS N
) Numbers
) TT
GROUP BY id, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10,GrpNumber
HAVING COUNT(*) >= 2
) TT
GROUP BY id
原始答案:
这是一种使用基于集合的查询的方法。此查询假设您的表名为 TableOfTen,并且它正好有 10 个 n[number][1..10] 列。它可以针对任何预先知道 n[number][...] 列数的表(或派生表)进行修改。
SELECT id, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, MAX(GrpSize) MaxSize, COUNT(GrpNumber) NumberOfSetsWithTwoOrMoreMembers
FROM (
SELECT id, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10,GrpNumber, COUNT(*) GrpSize
FROM
SELECT id, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10,
CASE Numbers.N
WHEN 1 THEN n1 - N
WHEN 2 THEN n2 - N
WHEN 3 THEN n3 - N
WHEN 4 THEN n4 - N
WHEN 5 THEN n5 - N
WHEN 6 THEN n6 - N
WHEN 7 THEN n7 - N
WHEN 8 THEN n8 - N
WHEN 9 THEN n9 - N
WHEN 10 THEN n10 - N
END GrpNumber
FROM `mytbl`
CROSS JOIN (
SELECT 1 AS N UNION ALL
SELECT 2 AS N UNION ALL
SELECT 3 AS N UNION ALL
SELECT 4 AS N UNION ALL
SELECT 5 AS N UNION ALL
SELECT 6 AS N UNION ALL
SELECT 7 AS N UNION ALL
SELECT 8 AS N UNION ALL
SELECT 9 AS N UNION ALL
SELECT 10 AS N
) Numbers
) TT
GROUP BY id, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10,GrpNumber
HAVING COUNT(*) > 2
) TT
GROUP BY id, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10