分组内联接返回太多记录

时间:2017-06-24 16:53:14

标签: sql sql-server tsql sql-server-2016

表有一个char的foundStatus列。我想返回一个findStatuses列表,旁边有一个计数 - 这有效:

SELECT foundstatus, count(foundstatus) as total
FROM findings f
WHERE findDateTime BETWEEN '2008-01-01' AND '2017-06-24 23:59:59'
group by foundstatus
order by foundstatus

我需要连接几个表来构建一个where子句 - 这样做会开始返回太多列。我可以让这个工作:

SELECT foundstatus, count(foundstatus) as total
FROM findings f left join
     pets p
     on f.petid = p.petid
WHERE findDateTime BETWEEN '2008-01-01' AND '2017-06-24 23:59:59' 
group by foundstatus
order by foundstatus

通过左连接,但是 - 我做的任何后续连接(左或内)只返回太多行(我猜是因为正在返回连接表中的多个记录):

SELECT foundstatus, count(foundstatus) as total
FROM findings f left join
     pets p
     on f.petid = p.petid inner join
     petTags pt
     ON p.petID = pt.petID 
WHERE findDateTime BETWEEN '2008-01-01' AND '2017-06-24 23:59:59' 
group by foundstatus
order by foundstatus

我需要一个类似于底部的语句,只有5个连接表才能返回与前2个查询相同的计数。我相信这很容易,但在谷歌上找不到任何东西 - 我怎么能这样做? THX。

1 个答案:

答案 0 :(得分:3)

假设您在findings中拥有主键,则可以执行以下操作:

select f.foundstatus, count(distinct f.findingsId) as total
from findings f left join
     pets p
     on f.petid = p.petid left join
     petTags pt
     on p.petID = pt.petID 
where f.findDateTime >= '2008-01-01' and
      f.findDateTime < '2017-06-25' 
group by f.foundstatus
order by foundstatus;

通常,count(distinct)不是最好的方法。我的猜测是EXISTS条款中的WHERE条件是做你想做的更好的方法。