简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM