我有以下查询:
SELECT saturday_combinations.index, v.val AS `row` , COUNT( * ) AS `count`
FROM saturday_combinations
INNER JOIN (
SELECT ONE AS val
FROM saturday_combinations
WHERE ONE IS NOT NULL
UNION
SELECT TWO AS val
FROM saturday_combinations
WHERE TWO IS NOT NULL
UNION
SELECT THREE AS val
FROM saturday_combinations
WHERE THREE IS NOT NULL
UNION
SELECT FOUR AS val
FROM saturday_combinations
WHERE FOUR IS NOT NULL
UNION
SELECT FIVE AS val
FROM saturday_combinations
WHERE FIVE IS NOT NULL
UNION
SELECT SIX AS val
FROM saturday_combinations
WHERE SIX IS NOT NULL
UNION
SELECT SEVEN AS val
FROM saturday_combinations
WHERE SEVEN IS NOT NULL
) v ON v.val = saturday_combinations.ONE
OR v.val = saturday_combinations.TWO
OR v.val = saturday_combinations.THREE
OR v.val = saturday_combinations.FOUR
OR v.val = saturday_combinations.FIVE
OR v.val = saturday_combinations.SIX
OR v.val = saturday_combinations.SEVEN
GROUP BY v.val
查询的目的是提供 saturday_combinations 表中 ONE、TWO、THREE、FOUR、FIVE、SIX 和 SEVEN 列中包含的不同值的计数。但是我想设置一个 desc 限制 4 以便它只根据最后 4 行(最后四个最大索引)执行计数。但我没有让它与工会合作。在最后添加 order 和 limit 仅限制最终选择,而不是获取最后 4 行并计算它们的分布。有小费吗?
表架构如下:
index | ONE|TWO|THREE|FOUR|FIVE|SIX|SEVEN
1 1 3 7 10 11 12 13
2 3 4 5 30 31 22 23
3 1 2 3 4 5 6 7
4 1 2 3 4 5 6 7
5 1 2 3 4 5 6 7
6 1 2 3 4 5 6 7
7 1 2 3 4 5 6 7
8 1 2 3 4 5 6 7
9 1 2 3 4 5 6 7
10 1 2 3 4 5 6 7
索引是自动递增的,ONE-SEVEN 具有整数值。
表中有大约 3000 行,我想根据最后 n 行计算每个值的出现次数。
Ideal result for the last n rows where n = last 3 rows should be
Numbers|Count
1 3
2 3
3 3
4 3
5 3
6 3
7 3
如果我增加 n 以包括最后 6 行,它们的计数应该会增加。如果我可以持续 10 行,那么计数应该会增加,并且其他数字应该与它们的计数一起出现。
这是一个真实表格示例的链接。 http://sqlfiddle.com/#!2/d035b