I have the following query:
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
The purpose of the query is to provide a count of the different values contained in the columns ONE,TWO,THREE,FOUR,FIVE,SIX and SEVEN in the table saturday_combinations. However I want to put a desc limit 4 so that it only performs the count based on the last 4 rows (last four maximum indexes). But I am not getting it to work with the union. Adding order and limit at the very end only limits from the final select, rather than get the last 4 rows and calculate the distribution on them. Any tips?
The table schema is as follows:
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
Index is auto-increment and ONE-SEVEN has integer values.
There are about 3000 rows in the table and I want to count occurences for each value based on the last n rows.
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
If I increase n to include last 6 rows their count should increase. If I could last 10 rows the count should increase and other numbers should appear with their count.
Here is a link to a sample of the real table.
http://sqlfiddle.com/#!2/d035b
If answer to my comment is
yesthen, you could try the following. When you need to addlimit, order bytounion selectsyou need to wrapunion querieswith brackets().Code:
If answer to my comment is
no, then please clarify.Here is the code based on your sample date:
EDIT as per OP has clarified and updated the question.
Quoted: “However I want to limit it so that it first takes the last n rows and then does the count on the values in those n rows. This means, if I have 3 columns with 3000 rows and 35 integers randomly appearing in these 3000 rows it should count how many times each integer appears.”
Query:
Output: