SQL Server 在SQL中的采样过程中折叠层

k97glaaz  于 2022-11-21  发布在  其他
关注(0)|答案(2)|浏览(141)

要在采样过程中获得每个层的方差,每个层至少需要2个元素。我需要将层3与其他层“折叠”(将层3的记录添加到其他层的记录中)。如果在这些情况下,默认要求该层与其上的层折叠(在这种情况下,如果必要,第一个层将与最后一个层折叠),则:
在SQL中有没有方法可以实现这种折叠?
我可以把第一桌带到第二桌吗?
|地层|频率|
| - -|- -|
| 一个|四个|
| 2个|六个|
| 三个|一个|
| 四个|10个|
|地层|频率|
| - -|- -|
| 一个|四个|
| 2个|七个|
| 四个|10个|
我将非常感谢你的回答。
我怀疑我可以使用“分析函数”,特别是沿着于“ROWS BEETWEEN 1 AND PRECEDING AND 1 FOLLOWING”这样的函数,再加上“IF”来识别记录少于2的行,但是我遇到了一些复杂的情况。

vtwuwzda

vtwuwzda1#

试试这个。对于你的数据库,用你的表名替换@t

--create temp table for testing
declare @t table
(
    strata int,
    frequency int
)

--insert values into temp table
insert into @t (strata, frequency) values
(1,4),(2,6),(3,1),(4,1),(5,10)

--intermediate table for final strata values
declare @tmp table
(
    s int
)

--final strata values are those with frequency bigger than/equal to 2
insert into @tmp (s) 
(
    select strata 
    from @t
    where frequency>=2
)

select 
normalisedStrata as strata, 
sum(frequency) as frequency 

from
(
    select 
    --normalise the strata by testing frequency
    case 
        when frequency<2 
        --if freq<2, get biggest element of temp table that's less than the row's strata
        then (select max(s) from @tmp where s<strata) 
        --otherwise just copy across
        else strata 
    end as normalisedStrata, 
    frequency
from @t
--subquery must be named, just put arbitrary string
) a
group by normalisedStrata
7jmck4yq

7jmck4yq2#

您可以这样做。使用case表达式检查Frequency,返回1或0作为指示符。对其执行累积求和以形成grp

with 
cte1 as
(
    select *, f = case when Frequency > 1 then 1 else 0 end
    from   strata
),
cte2 as
(
    select *, grp = sum(f) over (order by Strata)
    from   cte1
)
select Strata = min(Strata), Frequency = sum(Frequency)
from   cte2
group by grp
order by Strata

相关问题