Well, it's unclear what you're actually trying to find. However, a big part of your problem is that you're using old-school, pre-ISO/ANSI join
syntax. If you refactor your join to use modern join
syntax, you'll get a query that looks somethinn (a lot, actually) like this:
select zName = z.zname ,
Total = count(*)
From ZTable z
join SLTable sl on sl.zID = z.zID
join STable s on s.sID = sl.sID
join SETable se on se.sID = s.sID
join SEETable see on see.etID = se.etID
and see.segID = 3
join SEGTable seg on seg.segID = see.segID
Group By z.zname
order by z.zname
I suspect that what you want to get is a list of all zNames
and their respect counts of having segID = 3
. Since you are using inner joins, you'll only ever see zNames
that have a match. What you can do is something like this:
select zName = z.zname ,
Total = sum(case see.segID when 3 then 1 else 0 end)
from ZTable z
left join SLTable sl on sl.zID = z.zID
left join STable s on s.sID = sl.sID
left join SETable se on se.sID = s.sID
left join SEETable see on see.etID = se.etID
group By z.zname
order by z.zname
The above will return every row from zTable
at least once, with null
values for the columns of any table for which no match was found. Then we group it and count the rows where segID
is 3.