SQL Server:像用户名一样组合

时间:2014-04-22 14:21:02

标签: sql-server

我正在尝试合并UserName行内的相似名称。

如果我有以下内容:

Bob Barker
Johnny Rogers
Bob Barker
Bob Barker
Neal String
Bobby McNight
Johnny Rogers

我希望它是:

Bob Barker
Johnny Rogers
Neal String
Bobby McNight

到目前为止,我的查询是:

SELECT [UserName]
    ,[AffNumber]
    ,[blah]
    ,[tDate]
    ,[DIF]     
FROM [WWebsite].[dbo].[Log], [WWebsite].[dbo].[Users]            
WHERE blah = '62055'
AND tDate > '2013-12-31 00:00:00' 
AND tDate < '2014-04-01 00:00:00'

虽然我确实得到了结果,但我仍然不知道UserName

更新

Log表格包含以下列:

id, UserId, DIF, WalkDate,...

Users表格包含以下列:

id, UserName, Weight,...

1 个答案:

答案 0 :(得分:0)

SELECT DISTINCT
    [UserName]
    ,[AffNumber]
    ,[blah]
    ,[tDate]
    ,[DIF]     
FROM [WWebsite].[dbo].[Log] a 
JOIN [WWebsite].[dbo].[Users] b on a.UserId = b.Id            
WHERE blah = '62055'
AND tDate > '2013-12-31 00:00:00' 
AND tDate < '2014-04-01 00:00:00'

如果有了那些你会得到重复项,你可以尝试这样做:

SELECT [UserName]
    ,max([AffNumber])
    ,max([blah])
    ,max([tDate])
    ,max([DIF])
FROM [WWebsite].[dbo].[Log]
JOIN [WWebsite].[dbo].[Users] b on a.UserId = b.Id      
WHERE blah = '62055'
AND tDate > '2013-12-31 00:00:00' 
AND tDate < '2014-04-01 00:00:00'
GROUP BY UserName