id one two thr fou five
1 37 84 1 68 10
2 72 50 87 41 67
3 66 30 89 57 48
4 29 27 35 75 36
5 2 72 9 1 55
6 33 89 17 40 64
7 70 90 63 26 54
8 36 19 51 43 61
9 10 61 20 44 84
10 2 41 43 65 87
我需要反复计算上表中的每个数字。
示例:
61=>1 because if you count from the bottom to the first 61 there's 1 row
26=>3 because if you count from the bottom to the first 26 there are 3 rows
9=>5 because if you count from the bottom to the first 9 there are 5 rows
and so on...
查询应为所有数字输出类似于以下内容的表:
Number Rows count
61 1
26 3
9 5
这里的问题是:如何在mySQL中反转计数?有特殊功能吗? 谢谢
答案 0 :(得分:1)
如果MySQL具有UNPIVOT
函数,那么这将更加清晰:
SELECT x.num, co.co - count(x.id) FROM
(SELECT count(id) as co FROM tab) as co,
(SELECT t.num, max(t.id) as 'id' FROM
(SELECT id, one as 'num' FROM tab
UNION
SELECT id, two as 'num' FROM tab
UNION
SELECT id, thr as 'num' FROM tab
UNION
SELECT id, fou as 'num' FROM tab
UNION
SELECT id, fiv as 'num' FROM tab) as t
GROUP BY t.num) as x
INNER JOIN
(SELECT id FROM tab) as y on x.id >= y.id
GROUP BY x.num, co.co
答案 1 :(得分:0)
如果您按照ID进行排序,您可以获得所需的计数(Count(*) - id)。
如果没有,我相信如果id不合适,你可以使用@curRow标签。看看其他这些问题:
MySQL get row position in ORDER BY
With MySQL, how can I generate a column containing the record index in a table?
答案 2 :(得分:0)
select COUNT(*) from TestTbl
where id > (select max(id) from TestTbl
where one='9' or two ='9' or three='9' or four='9' or five='9')
select COUNT(*) from TestTbl
where id > (select max(id) from TestTbl
where one='26' or two ='26' or three='26' or four='26' or five='26')
select COUNT(*) from TestTbl
where id > (select max(id) from TestTbl
where one='61' or two ='61' or three='61' or four='61' or five='61')
答案 3 :(得分:0)
这是我提出的。这太丑了。
select num, t1.max - t2.id as reverse_count from
(select max(id) as max from testtable) as t1,
(select id, row1 as num from testtable union all select id,
row2 as num from testtable union all select id,
row3 as num from testtable union all select id,
row4 as num from testtable) as t2;
已修改为使用正确的命名架构
select num as Number, t1.max - t2.id as RowsCount from
(select max(id) as max from testtable) as t1,
(select id, one as num from testtable union all select id,
two as num from testtable union all select id,
thr as num from testtable union all select id,
fou as num from testtable union all select id,
five as num from testtable) as t2;