Al Lelopath
Al Lelopath

Reputation: 6778

Combine multiple rows into one

I have data that looks like this;

Id  Name        Number  Birthdate   
0   Dajit Singh NULL    6/9/2007  
5   Dajit Singh 12345   NULL   
11  Dajit Singh NULL    NULL

I want to progammatically combine these rows into 1 row with all data available:

0   Dajit Singh 12345   6/9/2007

Here's what I've got so far, but it doesn't do it:

Select Id, 
       Max(Name)   As Name, 
       Max(Number)    As Number, 
       Max(Birthdate) As Birthdate 
From   tblPerson 
Group By Id, Name, Number, Birthdate
Order By Name

How can this be accomplished?

Upvotes: 0

Views: 66

Answers (1)

Alexander I.
Alexander I.

Reputation: 2714

Please check the script:

DECLARE @table TABLE
(
    Id          INT NOT NULL,
    Name        VARCHAR(50) NOT NULL,
    Number      INT NULL,
    Birthdate   DATETIME NULL
)


INSERT INTO @table(Id, Name, Number, Birthdate) VALUES
(0, 'Dajit Singh', NULL, '20070906'),
(5, 'Dajit Singh', 12345, NULL),
(11, 'Dajit Singh', NULL, NULL),
(100, 'Alex', NULL, '20080906'),
(500, 'Alex', 12345, NULL),
(1100, 'Alex', NULL, NULL)


SELECT
    MIN(Id) As Id, 
    Name As Name, 
    MAX(Number) As Number, 
    MAX(Birthdate) As Birthdate 
FROM @table
GROUP BY Name
ORDER BY Name

Upvotes: 1

Related Questions