在SQL的以下段中完成交叉表的正确方法是什么?

时间:2018-10-16 20:14:14

标签: sql crosstab

我以标准方式在SQL的一列上创建频率。 我的代码是

select id , count(*) as counts   
from TABLE    
group by id   
order by counts desc

假设六个id的输出如下

 id  counts
 --  -----
 1    3  two id have 3 counts per
 2    3 
 ---------
 3    6  three id have 6 counts per
 4    6
 5    6
 ---------
 6    2  one id has 2 counts

如何产生以下内容?

nid  counts
---  ------
 1     2
 2     3
 3     6

我正在蜂巢环境中书写,但这应该是标准SQL。 预先感谢您的回答。

2 个答案:

答案 0 :(得分:0)

您需要两个聚合级别:

select counts, count(*)
from (select id , count(*) as counts   
      from TABLE    
      group by id 
     ) c  
group by counts
order by counts;

我将此称为“直方图直方图”查询。我通常在外部min(id)中包含max(id)select,所以我有具有给定频率的id的示例。

答案 1 :(得分:0)

尝试一下:

SELECT count(*) as nid, counts
FROM 
(select id , count(*) as counts   
      from TABLE    
      group by id 
) a  
GROUP BY counts
ORDER BY counts;