I couldn\'t be more specific in the title part but I want to do something a little bit complex for me. I thought I did it but it turned out that it is buggy.
I have
I might switch the query slightly to this:
select p.addDate,
p.idOwner,
a.Username,
p.idProject,
p.price,
o.OfferCount
from project p
left join
(
select count(*) OfferCount, idproject
from offer
group by idproject
) o
on p.idproject = o.idproject
left join account a
on p.idowner = a.idaccount
This way, you are getting the count
by the projectid
and not based on all of the other fields you are grouping by. I am also using a LEFT JOIN
in the event the projectid
or other id doesn't exist in the other tables, you will still return data.
Your question is a bit vague, but here are some pointers:
ORDER BY offercount
.GROUP BY Project.idProject
first before the other fields.An inner query can be made either in the FROM
clause, as suggested by other answers, or directly in the SELECT
clause, like so:
SELECT Project.idProject,
(SELECT COUNT(Offer.idOffer)
FROM Offer
WHERE Offer.idProject = Project.idProject
) AS OfferCount
FROM Project
Try this (modified for projects with no offers):
SELECT
Project.addDate,
Project.idOwner,
Account.Username,
Project.idProject,
Project.Price,
ISNULL(q.offercount, 0) AS offercount
FROM
(
SELECT
o.idProject,
COUNT(o.idProject) as offercount
FROM Offer o
GROUP BY o.idProject
) AS q
RIGHT JOIN Project ON Project.idProject = q.idProject
INNER JOIN Account ON Account.idAccount = Project.idOwner
ORDER BY addDate DESC