Could someone help me figure out what’s wrong with the following T-SQL syntax?
SELECT
p.CompanyId, COUNT(*) as PolicyCount, c.CompanyId, c.CompanyName
FROM
dbo.Policy p
INNER JOIN dbo.Company c ON p.CompanyId = c.CompanyId
WHERE
p.PolicyIssuingDate BETWEEN @StartDate AND @EndDate
GROUP BY
p.PolicyId
I keep getting the following syntax error:
Column 'dbo.Policy.CompanyId' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Any suggestions?
UPDATE:
Ok thanks to your input guys, I figured it out… Here’s the solution:
SELECT
p.CompanyId, COUNT(p.PolicyId) as PolicyCount, c.CompanyName
FROM
dbo.Policy p
INNER JOIN dbo.Company c ON p.CompanyId = c.CompanyId
WHERE
p.PolicyIssuingDate BETWEEN @StartDate AND @EndDate
GROUP BY
p.CompanyId, c.CompanyName
According to your query u are trying to count records which have same policyID and whose issue date is between @startdate and @enddate
But the problem is u select companyid which is not in group by clause