0

I have the bellow data set output should come like less then one frequency.. i am new to sql so don't have much idea..

in the input i have 3 times 1, 2 times 2, 3 times 3 and 2 times 4. output i want 2 times 1, 1 time 2, 2 times 3 and 1 time 4..

Any suggestion how to achieve this output!!

enter image description here

Ankur Alankar Biswal
  • 1,184
  • 1
  • 12
  • 23

1 Answers1

1

This can be written in a more compact form, but just for clarity:

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

Expression to replicate the row taken from SQL: Repeat a result row multiple times...

jpw implementation (please feel free to copy it into your own answer):

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
Community
  • 1
  • 1
Y.B.
  • 3,526
  • 14
  • 24
  • Updated following clarification in comments to the question – Y.B. Jul 01 '16 at 11:26
  • 2
    You could partition the data in the row_number function and filter out rows with number 1. It should be more efficient: Something like `numbers as ( select id, row_number() over (partition by id order by id) as n from src ) select id from numbers where n <> 1` It renders a better looking execution plan in my test. – jpw Jul 01 '16 at 11:47