我有一个带有用户输入的表格。我想计算每个用户的输入数量,根据数量进行排序,然后找到行号。
换句话说,我想根据输入的数量找到每个用户的排名。
该数据库位于PostgreSQL 8.4中。似乎没有任何性能问题。该表的行数少于1000000。
这是重复项 this个问题。 可悲的是,该问题的得分为-3,没有答案。
该表名为table1,user_name列具有唯一的用户。
user_name | input
name1 txt input 1
name2 txt input 2
name1 txt input 3
name3 txt input 4
name1 txt input 5
name2 txt input 6
我想要的查询是带有一项附加功能的
WITH temp_table AS (
SELECT user_name, COUNT(*)
FROM table1
GROUP BY user_name
ORDER by count DESC )
SELECT name, row_number() OVER ( ) FROM temp_table;
输出:
user_name | row_number
name1 1
name2 2
name3 3
如何使用user_name从该表中选择一行?我尝试过:
WITH temp_table AS (
SELECT user_name, COUNT(*)
FROM table1
GROUP BY user_name
ORDER by count DESC )
SELECT name, row_number() OVER ( ) FROM temp_table
WHERE user_name = 'name2';
输出始终为row_number 1
user_name | row_number
name2 1
我期望
user_name | row_number
name2 2
答案 0 :(得分:3)
您可以在基本查询中直接将row_number()
与group by
组合在一起。
select *
from (
select user_name,
count(*) as cnt,
row_number() over (order by count(*) desc) as rn
from table1
group by user_name
) t
where user_name = 'name2';
之所以起作用,是因为group by
在窗口函数之前被求值。您也可以将其写为CTE:
with temp_table as (
select user_name,
count(*) as cnt,
row_number() over (order by count(*) desc) as rn
from table1
group by user_name
)
select *
from temp_table
where user_name = 'name2';
您的row_number()
不起作用,因为您的where
子句将结果限制为一行,并且在where
子句之后 应用了窗口函数。>
答案 1 :(得分:1)
您可以在下面尝试-只需使用子查询
WITH temp_table AS (
SELECT user_name, COUNT(*)
FROM table1
GROUP BY user_name
ORDER by count DESC
)
select * from
(
SELECT name, row_number() OVER (order by null) FROM temp_table
)A where name='name2'