通过比较频率来分离值列表

时间:2016-07-01 10:19:57

标签: sql sql-server

我的波纹管数据集输出应该低于一个频率.. 我是sql的新手,所以没有多少想法..

在输入中我有3次1,2次2,3次3次和2次4.输出我要2次1次,1次2次,2次3次和1次4次..

任何建议如何实现此输出!!

enter image description here

1 个答案:

答案 0 :(得分:1)

这可以用更紧凑的形式编写,但为了清楚起见:

With Src As (        --< Source table
    Select * From (Values (1),(2),(3),(1),(1),(2),(3),(3),(4),(4),(5)) V (Id)
), Numbers As (      --< Auxiliary table with numbers from 1 to maximum row count of Src
    Select ROW_NUMBER() Over (Order By Id) As N From Src
), Counted As (      --< Calculate current number of ID occurances
    Select Id, Count(Id) As Cnt From Src Group By Id
)
    Select Id
    From Counted                 --< From distinct list of IDs
    Inner Join Numbers           --< replicate each row
    On Numbers.N < Counted.Cnt   --< one less time than the Cnt

表达式复制从SQL: Repeat a result row multiple times...

获取的行

jpw实施(请随时将其复制到您自己的答案中)

With Src As (                                --< Source table
    Select * From (Values (1),(2),(3),(1),(1),(2),(3),(3),(4),(4),(5)) V (Id)
), Numbered As (                             --< Number ID occurances
    Select Id, row_number() Over (Partition By id Order By id) As n From Src
)
    Select Id From Numbered Where n > 1      --< Take one off