gpt4 book ai didi

sql-server - 在 SQL Server 中生成直方图

转载 作者:行者123 更新时间:2023-12-04 04:59:53 28 4
gpt4 key购买 nike

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

这个想法是将所有价格分成 100 个大小相同(基于价格)的桶,然后每个桶包含许多在桶的最小值和最大值内定价的项目。 NTILE 不起作用——它试图在存储桶之间平均分配项目(基于计数)。

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

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 来完成此任务或更好的方法?

谢谢

最佳答案

大概是这样的:

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
;

这很好地产生了这个直方图:
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

请记住首先将您的数据转换为单行。

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

关于sql-server - 在 SQL Server 中生成直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16268441/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com