SQL Distinct从多个数据库中的多个列计数

时间:2013-06-21 18:20:29

标签: sql count distinct

这是我到目前为止所做的:

SELECT p2.fullname[UploadedBy], p.fullname[UploadedTo]
from docexchange d (NOLOCK)

left join exchange_permissions r on r.file_id = d.id
inner join people p on r.people_id = p.id
inner join people p2 on d.upload_by_id = p2.id

where upload_date > '2013-05-21'

此查询返回大约8000个结果 - 如果我将DISTINCT添加到我的SELECT语句中,则返回大约900个结果 - 我想获得这900个结果,但我需要另一个列告诉我如何很多时候,这些结果出现在数据库中。

我试过这样做:

Select p2.fullname, p.fullname, COUNT(DISTINCT p2.fullname + p.fullname)

但是返回错误:列'people.fullname'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

1 个答案:

答案 0 :(得分:2)

您需要group by

SELECT p2.fullname as [UploadedBy], p.fullname as [UploadedTo], count(*)
from docexchange d (NOLOCK)

left join exchange_permissions r on r.file_id = d.id
inner join people p on r.people_id = p.id
inner join people p2 on d.upload_by_id = p2.id

where upload_date > '2013-05-21'
group by p2.fullname, p.fullname