0

i have a SQL table like this:

id      pNum
-----   --------
100     12
100     13
100     15
100     16
100     17
200     18
200     19
300     20
300     21
300     25

and i want to group by the id and the pNum sequences, and count the number of rows. having a result like this.

id      res
-----   --------
100     2
100     3
200     2
300     2
300     1

any idea on how to do it?

7
  • 2
    what rdbms are you using?
    – Taryn
    Feb 7, 2013 at 15:45
  • what res does represent in the grouped table Feb 7, 2013 at 15:46
  • Micorsoft SQL ----------------- Feb 7, 2013 at 15:48
  • Oh, you're grouping "res" as continuous sequences, right? Feb 7, 2013 at 15:48
  • res is the count of id grouped by sequences of pnum Feb 7, 2013 at 15:48

2 Answers 2

4

If your DBMS supports window functions (e.g. SQL Server 2005+)

SELECT id,
       count(*) AS res
FROM   (SELECT *,
               [pNum] - ROW_NUMBER() OVER (PARTITION BY [id] ORDER BY [pNum]) AS Grp
        FROM   YourTable) T
GROUP  BY id,
          Grp 

SQL Fiddle

2
  • 2
    @user2051336 - This type of requirement is often known as finding "gaps and islands". The approach in my answer is attributed to Itzik Ben Gan AFAIK. What version of SQL Server are you on? Feb 7, 2013 at 15:59
  • @MartinSmith - This one might also be useful for MS SQL server stackoverflow.com/a/4324654/247184 Sep 4, 2014 at 20:25
2

Using the solution from this question:

declare @table table
(
    id int
    , pnum int
)


insert into @table
values (100,    12)
, (100,     13)
, (100,     15)
, (100,     16)
, (100,     17)
, (200,     18)
, (200,     19)
, (300,     20)
, (300,     21)
, (300,     25)

;WITH numbered AS (
  SELECT
    ID, pnum,
    SeqGroup = ROW_NUMBER() OVER (PARTITION BY ID ORDER BY pnum) - pnum
  FROM @table
)
SELECT
  ID,
  COUNT(*) AS res
FROM numbered
GROUP BY ID, SeqGroup
ORDER BY id, MIN(pnum)
4
  • 1
    Nice trick with the row_number() - pnum. What does this assignement thing SeqGroup = do?
    – user330315
    Feb 7, 2013 at 15:59
  • @a_horse_with_no_name - As I suspect you are probably aware it is a SQL Server specific way of aliasing columns. Feb 7, 2013 at 16:01
  • @MartinSmith: not really. Is there a difference to the as foo standard syntax?
    – user330315
    Feb 7, 2013 at 16:03
  • @a_horse_with_no_name - Not really. Some people (such as Aaron Bertrand) prefer it as it is easier to lime up the column aliases. Bad Habits to Kick : Using AS instead of = for column aliases Feb 7, 2013 at 16:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.