为什么 count(column_name) 会这样?

Why is count(column_name) behaving like this?

考虑关系帐户(客户、余额),其中客户是主键并且没有空值。

我想根据余额递减对客户进行排名。 (余额最大的客户获得排名 1。并没有打破平局,但排名被跳过:如果恰好有两个客户的余额最大,他们各自获得排名 1 并且不分配排名 2。)

为什么下面的查询从不打印等级为 1 的客户?

    select A.customer, 1+count(B.customer) 
    from account A, account B 
    where A.balance < B.balance 
    group by A.customer 

SQLfiddle Link

以下语句将根据余额为您提供所有客户的排名:

SELECT A.customer, A.balance, ( 
    SELECT count(*)+1 
    FROM account B
    WHERE A.balance < B.balance
  ) AS rank
FROM account A ORDER BY A.balance DESC

结果将是:

customer balance rank
P   500 1 
Q   400 2 
R   400 2 
S   300 4

order by A.balance 进行排序,而 desc 从大到小排序。最后,子查询提供排名(注意 +1)。

这是一个示例 fiddle

这与计数无关。

您正在 A 和 B 之间进行连接,并且仅显示 A.balance < B.balance 的记录,因为您的顶级客户没有这样的记录(根据定义,没有帐户更高的余额)你没有得到任何记录。

这应该可以解决问题

select A.customer, ( 
    select count(*) + 1 
    from account B
    where A.balance < B.balance
) from account A

尝试

select A.customer, 
(select count(*) from account) -
(select count(*) from account a1 where a1.balance<a.balance) rank
from account A
Order by rank

让我们试试这个Example

排名不跳级

set @number:=0;
set @balance:=0;

select customer, balance, rank 
from (
  select 
    *, 
    @number:=if(@balance=balance, @number, @number+1) as rank,
    @balance:=balance
  from account
  order by balance
) as rankeddata;

结果

customer balance rank
S        300     1
Q        400     2
R        400     2
P        500     3

要显示排名从 500 -> 300,只需将 ORDER BY balance 更改为 ORDER BY balance DESC

如果多行具有相同的排名则跳过排名

如果您希望跳过分配的排名,您可以稍微调整查询 SQL Fiddle

set @number:=0;
set @balance:=0;
set @rank_reused:=0;

select customer, balance, rank
from (
  select 
    *, 
    @number:=if(@balance=balance, @number, @number+1+@rank_reused) as rank,
    @rank_reused:=if(@balance=balance, @rank_reused+1, 0) as reused,
    @balance:=balance
  from account
  order by balance desc
) as rankeddata;

结果

customer balance rank
S        300     1
Q        400     2
R        400     2
P        500     4