3

例如,我有表:

ID   |   Value
1         hi
1         yo
2         foo
2         bar
2         hehe
3         ha
6         gaga

我希望我的查询得到 ID、Value;同时返回的集合应该按照每个ID的频率计数顺序。

我尝试了下面的查询,但不知道如何同时获取 ID 和 Value 列:

SELECT COUNT(*) FROM TABLE group by ID order by COUNT(*) desc;

计数对我来说无关紧要,我只需要数据按这样的顺序排列。

愿望结果:

ID   |   Value

2         foo
2         bar
2         hehe
1         hi
1         yo
3         ha
6         gaga

As you can see because ID:2 appears most times(3 times), it's first on the list, 
then ID:1(2 times) etc. 
4

4 回答 4

5

你可以试试这个 -

    select id, value, count(*) over (partition by id)  freq_count
from
(
select 2  as ID,  'foo' as value
from dual
union all
select 2,         'bar'
from dual
union all
select 2,         'hehe'
from dual
union all
select 1 ,        'hi'
from dual
union all
select 1  ,       'yo'
from dual
union all
select 3   ,      'ha'
from dual
union all
select 6    ,     'gaga'
from dual
)
order by 3 desc;
于 2013-10-07T06:10:37.037 回答
4

像这样的东西怎么样

SELECT  t.ID,
        t.Value,
        c.Cnt
FROM    TABLE t INNER JOIN
        (
            SELECT  ID,
                    COUNT(*) Cnt
            FROM    TABLE
            GROUP BY ID
        ) c ON  t.ID = c.ID
ORDER BY c.Cnt DESC

SQL 小提琴演示

于 2013-10-07T05:58:14.070 回答
4
select t.id, t.value
from TABLE t
inner join 
(
  SELECT id, count(*) as cnt 
  FROM TABLE 
  group by ID
)
x on x.id = t.id
order by x.cnt desc
于 2013-10-07T05:59:08.033 回答
1

我看到问题已经回答了,但是由于缺少最明显和最简单的解决方案,所以我还是发布了它。它不使用自连接或子查询:

SQL> create table t (id,value)
  2  as
  3  select 1, 'hi' from dual union all
  4  select 1, 'yo' from dual union all
  5  select 2, 'foo' from dual union all
  6  select 2, 'bar' from dual union all
  7  select 2, 'hehe' from dual union all
  8  select 3, 'ha' from dual union all
  9  select 6, 'gaga' from dual
 10  /

Table created.

SQL> select id
  2       , value
  3    from t
  4   order by count(*) over (partition by id) desc
  5  /

        ID VALU
---------- ----
         2 bar
         2 hehe
         2 foo
         1 yo
         1 hi
         6 gaga
         3 ha

7 rows selected.
于 2013-10-07T10:39:22.687 回答