如何通过postgresql中没有group by的字段的count()来查询查询结果

时间:2014-02-18 05:21:03

标签: sql postgresql

我有简单的数据库,我的答案应该是这么简单,但我找不到我的答案db看起来像:

-----------------
name | ip
-----------------
nick |192.168.1.10
john |192.168.1.1
john |192.168.1.2
john |192.168.1.3
lucy |192.168.10.1
lucy |192.168.10.2

我需要一个返回所有行的查询,但结果按每个名称的count(ip)排序 以上列表的结果应该是:

------------------
name |ip
------------------
nick |192.168.1.10
lucy |192.168.10.1
lucy |192.168.10.2
john |192.168.1.1
john |192.168.1.2
john |192.168.1.3

4 个答案:

答案 0 :(得分:1)

这是SQL Fiddle

试试这句话。

SELECT * FROM tblSAMPLE ORDER BY name DESC,ip

答案 1 :(得分:1)

尝试此查询:

SELECT t1.* 
FROM   table1 t1 
       INNER JOIN (SELECT Count(name) counter, 
                          name 
                   FROM   table1 
                   GROUP  BY name)t2 
               ON t1.name = t2.name 
ORDER  BY counter; 

SQL Fiddle

答案 2 :(得分:0)

SELECT NAME,IP,
       COUNT(NAME) KEEP (DENSE_RANK LAST ORDER BY NAME) 
               OVER (PARTITION BY NAME) "Answer"
FROM PSQL
ORDER BY 3

Ans By Subash M

需要说出正确答案Y / N?

答案 3 :(得分:0)

这应该比桌面上的自联接更快。

select name, ip
from (
  select name,
         ip,
         count(*) over (partition by name) as cnt
  from the_table
) t
order by cnt;