我有一个有两个表的数据库: 表1有用户 表2包含这些用户的代表
如果可能,我想在一个查询中执行以下操作:
我已经完成了第1步和第2步,但是如果可能的话,不知道如何实现步骤#3。这是我到目前为止的查询:
Select distinct users.UserID, Count(delegates) as 'Number of Delegates'
From delegates
inner Join users on delegates.delegates = users.handle
Group by Users.UserID
Order by Count(delegates) desc
答案 0 :(得分:1)
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
Select distinct users.UserID,
COUNT(delegates) as 'Number of Delegates',
GROUP_CONCAT(delegates.delegate_id SEPARATOR ',') as 'Delegate list'
From delegates
inner Join users on delegates.delegates = users.handle
Group by Users.UserID
Order by Count(delegates) desc
答案 1 :(得分:1)
以下是SQL-Server解决方案:
Select * From
(
Select users.UserID, users.handle, Count(delegates) as 'Number of Delegates'
From delegates
inner Join users on delegates.delegates = users.handle
Group by Users.UserID, users.handle
) myTbl
Inner Join delegates d
on delegates.delegates = myTble.handle
Order by 'Number of Delegates' desc
答案 2 :(得分:0)
由于您已按用户ID分组,因此无法在Select子句中使用代理ID。 您拥有的一个选项是按userID和DelegateID进行分组,但缺点是相同的计数会重复多次。