0
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 中反转计数?有什么特殊功能吗?谢谢

4

4 回答 4

1

UNPIVOT如果 MySQL 有一个函数,这会更干净:

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
于 2012-08-29T14:04:20.197 回答
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;
于 2012-08-29T13:27:06.893 回答
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')
于 2012-08-29T13:02:09.340 回答
0

如果您按应该执行的 id 排序,则可以使用 (Count(*) - id) 获得所需的计数。

如果没有,我相信如果 id 不按顺序,您可以使用 @curRow 标签。看看这些其他问题:

MySQL在ORDER BY中获取行位置

使用 MySQL,如何在表中生成包含记录索引的列?

于 2012-08-29T12:43:03.603 回答