我有以下查詢:SQL服務器:合併同類行
SELECT DISTINCT [WL].[Id]
,[WL].[UserId]
,[WL].[DIF]
,[WL].[MW]
,[WL].[Notes]
,[WL].[WDate]
,[WL].[CB]
,[WL].[MPH]
,[U].[Id]
,[U].[UserName]
,[U].[We]
,[U].[SLength]
,[U].[UP]
,[U].[PU]
,[U].[ANumber]
,[U].[G_CK]
FROM
[Wsite].[dbo].[WLog] as WL
INNER JOIN
[Wsite].[dbo].[Users] AS U ON [U].[Id] = [WL].[UserId]
WHERE
[WL].[WDate] >= CONVERT(datetime, '2012-01-01 00:00:00', 120)
AND [WL].[WDate] <= CONVERT(datetime, GETDATE(), 120)
GROUP BY
[WL].[UserId]
而我得到的錯誤是:
列「Wsite.dbo.WLog.Id」是在選擇無效 列表,因爲它不包含在聚合函數或 GROUP BY子句中。
我想要的只是在列表中有多個UserID
的情況下合併數據。
作爲一個例子:
Id | UserId | .... | Id | UserName | SLength | ....
5843| 99304 | .... | 99304| Bob Barker | 14 | ....
5844| 06300 | .... | 06300| Dean Martin | 104 | ....
5845| 99304 | .... | 99304| Bob Barker | 8 | ....
5846| 99304 | .... | 99304| Bob Barker | 11 | ....
5847| 7699 | .... | 7699 | John Doe | 0 | ....
因此,它應該是這樣的:
Id | UserId | .... | Id | UserName | SLength | ....
5843| 99304 | .... | 99304| Bob Barker | 33 | ....
5844| 06300 | .... | 06300| Dean Martin | 104 | ....
5847| 7699 | .... | 7699 | John Doe | 0 | ....
注意鮑勃巴克的SLength合併(14 + 8 + 11 = 33)。
任何幫助將是偉大的!謝謝!
UPDATE
SELECT DISTINCT
MIN([WL].[Id]) AS [WLID]
,MIN([WL].[UserId]) AS [WLUD]
,SUM([WL].[DIF]) AS [DIF]
,SUM([WL].[MW]) AS [MW]
,[WL].[Notes]
,[WL].[WDate]
,SUM([WL].[CB]) AS [CB]
,SUM([WL].[MPH]) AS [MPH]
,MIN([U].[Id] AS [UID]
,MIN([U].[UserName] AS [UUserName]
,[U].[We]
,SUM([U].[SL]) AS [SL]
,[U].[UP]
,[U].[PU]
,[U].[ANumber]
,[U].[G_CK]
FROM [Wsite].[dbo].WLog as WL
INNER JOIN [Wsite].[dbo].[Users] AS U
ON [U].[Id] = [WL].[UserId]
WHERE [WL].[WDate] >= CONVERT(datetime, '2012-01-01 00:00:00', 120)
AND [WL].[WDate] <= CONVERT(datetime, GETDATE(), 120)
GROUP BY
[WL].[Notes]
,[WL].[WDate]
,[U].[We]
,[U].[UP]
,[U].[PU]
,[U].[ANumber]
,[U].[G_CK]
ORDER BY [U].[UserName] DESC
爲所有其它領域也會包含除'Id'場和'SLength'字段相同的數據的? – Linger