I currently have two table where a versionLog can contain many ProductVersions.
Following Sql Query:
SELECT versionlog.[Name], ( SELECT COUNT(*) FROM dbo.ProductVersions productVersion WHERE productVersion.VersionLogId = versionLog.Id ) AS ProductVersions FROM dbo.Versionlog versionLog
produces a result set similar to
Name | ProductVersions Log1 | 12 Log2 | 6 Log3 | 0
etc..
How can I limit the result set to only return Versionlogs with a ProductVersion Count = 0?
According to google I’ll need to use the Having
clause?
Advertisement
Answer
Using HAVING
:
SELECT versionlog.[Name] FROM dbo.Versionlog versionLog LEFT JOIN dbo.ProductVersions productVersion ON productVersion.VersionLogId = versionLog.Id GROUP BY versionlog.[Name] HAVING COUNT(productVersion.VersionLogId) = 0;
And without grouping:
SELECT versionlog.[Name] FROM dbo.Versionlog versionLog LEFT JOIN dbo.ProductVersions productVersion ON productVersion.VersionLogId = versionLog.Id WHERE productVersion.VersionLogId IS NULL