首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在SQL Server中生成直方图

在SQL Server中生成直方图
EN

Stack Overflow用户
提问于 2013-04-29 06:02:54
回答 1查看 4.1K关注 0票数 2

我使用的是SQL Server 2012,需要生成一个概念上类似于Google's screener的直方图

其思想是将所有价格划分为100个大小相等(基于价格)的存储桶,然后每个存储桶包含一些在存储桶的最小和最大定价范围内定价的商品。NTILE不起作用--它试图在存储桶中平均地划分项目(基于计数)。

所以,这就是我到目前为止所得到的:

代码语言:javascript
运行
复制
select bucket, count(*) from (select cast((PERCENT_RANK() OVER(ORDER BY Price DESC)) *   100 as int) as bucket  from MyTable
where DataDate = '4/26/2012') t group by bucket

这是在SQL Server 2012中生成直方图的好方法吗?SQL Server 2012有没有内置的功能或更好的方法来完成此任务?

谢谢

EN

回答 1

Stack Overflow用户

发布于 2013-04-29 08:37:04

也许是这样:

代码语言:javascript
运行
复制
with cte as (
  select base = 1 + u + t*3 from (
    select 0 as u union all select 1 union all select 2
  ) T1
  cross join (
    select 0 as t union all select 1 union all select 2
  ) T2
), data as (
  select * 
  from ( 
   values (1,1,2,3,3,5,7,4,2,1)
  ) data(x0,x1,x2,x3,x4,x5,x6,x7,x8,x9)
)
select cte.base
  ,case when x0>=base then 'X' else  ' ' end as x0
  ,case when x1>=base then 'X' else  ' ' end as x1
  ,case when x2>=base then 'X' else  ' ' end as x2
  ,case when x3>=base then 'X' else  ' ' end as x3
  ,case when x4>=base then 'X' else  ' ' end as x4
  ,case when x5>=base then 'X' else  ' ' end as x5
  ,case when x6>=base then 'X' else  ' ' end as x6
  ,case when x7>=base then 'X' else  ' ' end as x7
  ,case when x8>=base then 'X' else  ' ' end as x8
  ,case when x9>=base then 'X' else  ' ' end as x9
from cte
cross join data
order by base desc
;

它很好地生成了这个直方图:

代码语言:javascript
运行
复制
base        x0   x1   x2   x3   x4   x5   x6   x7   x8   x9
----------- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
9                                                         
8                                                         
7                                         X               
6                                         X               
5                                    X    X               
4                                    X    X    X          
3                          X    X    X    X    X          
2                     X    X    X    X    X    X    X     
1           X    X    X    X    X    X    X    X    X    X

记住先将数据旋转到单行中。

要获得更紧凑的表示形式,请将各种数据列连接成一个长字符串。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16268441

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档