使用空行进行SQL分组

时间:2012-11-09 17:35:45

标签: sql sql-server tsql group-by

我搜索了一下,找不到能解决我确切问题的任何内容

我有一个表(MSSQL),数据如下所示:

Source table:

RID    FullName FirstName   LastName    Email               Address
-------------------------------------------------------------------------------
1      NULL     [BOB]       NULL        NULL                NULL
1      NULL     NULL        [BOB]       NULL                NULL
1      NULL     NULL        NULL        [bob@bob.com]       NULL
2      NULL     [JAY]       NULL        NULL                NULL
2      NULL     NULL        [JAY]       NULL                NULL
2      NULL     NULL        NULL        [jerry@jerry.com]   NULL
3      NULL     [RICK]      NULL        NULL                NULL
3      NULL     NULL        [RICK]      NULL                NULL
3      NULL     NULL        NULL        [rick@rick.com]     NULL

但我需要将数据转换为如下所示:

Results table:

RID     FullName             Email                Address
---------------------------------------------------------
1       [BOB] [BOB]        [bob@bob.com]          NULL
2       [JAY] [JAY]        [jerry@jerry.com]      NULL
3       [RICK] [RICK]      [rick@rick.com]        NULL

注意:如果源表中的Fullname为NULL,则我们将FirstName和LastName组合在一起。 (如果FirstName和LastName都是NULL,那么我们只需要一个NULL FullName结果,这完全没问题。)

提前感谢您提供任何帮助!

2 个答案:

答案 0 :(得分:4)

您需要group by

select rid, coalesce(max(FullName), max(FirstName)+' '+max(LastName)) as FullName,
       max(Email) as Email,
       max(Address) as Address
from t
group by rid
order by 1

答案 1 :(得分:2)

这是一种方式,虽然有点复杂。我不知道您的完整数据集,但如果每个RID 有多个条目(例如,具有不同FirstName值的多个行),则应该为您提供所有可能的组合。

SELECT a.RID, b.FirstName + ' ' + c.LastName AS FullName, d.Email
FROM myTable a
LEFT OUTER JOIN myTable b ON a.RID = b.RID AND b.FirstName IS NOT NULL
LEFT OUTER JOIN myTable c ON a.RID = c.RID AND c.LastName IS NOT NULL
LEFT OUTER JOIN myTable d ON a.RID = d.RID AND d.Email IS NOT NULL
GROUP BY a.RID, b.FirstName, c.LastName, d.Email

SQL Fiddle example