dbTalk Databases Forums  

Grouping similar rows

comp.databases.ms-sqlserver comp.databases.ms-sqlserver


Discuss Grouping similar rows in the comp.databases.ms-sqlserver forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
jan_soderman@yahoo.se
 
Posts: n/a

Default Grouping similar rows - 09-05-2007 , 09:59 AM






Hi

I would like to group rows based on order and similarity in a single
sql-query if possible:

A, 1, 50
A, 2, 50
A, 3, 100
A, 4, 50
A, 5, 100
A, 6, 100

Would come out as:

A, 1, 50, 2 <-- Last value shows number of grouped rows
A, 2, 100, 1
A, 3, 50, 1
A, 4, 100, 2

Any suggestions?


Reply With Quote
  #2  
Old   
Hugo Kornelis
 
Posts: n/a

Default Re: Grouping similar rows - 09-05-2007 , 02:17 PM






On Wed, 05 Sep 2007 07:59:32 -0700, jan_soderman (AT) yahoo (DOT) se wrote:

Quote:
Hi

I would like to group rows based on order and similarity in a single
sql-query if possible:

A, 1, 50
A, 2, 50
A, 3, 100
A, 4, 50
A, 5, 100
A, 6, 100

Would come out as:

A, 1, 50, 2 <-- Last value shows number of grouped rows
A, 2, 100, 1
A, 3, 50, 1
A, 4, 100, 2

Any suggestions?
Hi Jan,

I believe that this will do what you need (SQL Server 2005 only):

CREATE TABLE TheInput
(Letter char(1) NOT NULL,
RowNum int NOT NULL,
OtherValue int NOT NULL,
PRIMARY KEY (Letter, RowNum));
go
-- Original testset
INSERT INTO TheInput (Letter, RowNum, OtherValue)
SELECT 'A', 1, 50
UNION ALL
SELECT 'A', 2, 50
UNION ALL
SELECT 'A', 3, 100
UNION ALL
SELECT 'A', 4, 50
UNION ALL
SELECT 'A', 5, 100
UNION ALL
SELECT 'A', 6, 100;
-- Extra testcases
INSERT INTO TheInput (Letter, RowNum, OtherValue)
SELECT 'B', 1, 50
UNION ALL
SELECT 'B', 2, 100
UNION ALL
SELECT 'B', 3, 50;
go
WITH CTE AS
(SELECT Letter, OtherValue,
ROW_NUMBER() OVER (PARTITION BY Letter
ORDER BY RowNum) AS rn1,
ROW_NUMBER() OVER (PARTITION BY Letter, OtherValue
ORDER BY RowNum) AS rn2
FROM TheInput)
SELECT Letter,
ROW_NUMBER() OVER (PARTITION BY Letter
ORDER BY MIN(rn1)) AS NewRowNumber,
OtherValue,
COUNT(*) AS NumberOfGroupedRows
FROM CTE
GROUP BY Letter, OtherValue, (rn1-rn2)
ORDER BY Letter, MIN(rn1);
go
DROP TABLE TheInput;
go

--
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis


Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.3
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.