When you use DISTINCT keyword, it determine the "distinctness" based on all the columns in the select list. So if there are two rows which have different approveddate (or any other column that are different), both rows will be returned even if the PermitNumber is the same for both of those rows.If you want to get only one row for a given permitnumber, you have to decide how to pick the other columns, for a given permit number. You could use a max function (see below) or you could use the row_number() function (see further down below):SELECT v.PermitNumber, max(p.ApprovedDate) AS ApprovedDate, max(v.ProcessStatus) AS ProcessStatus, max(v.PermitTypeDescription) AS PermitTypeDescription, max(v.ServiceAddress) AS ServiceAddress, max(v.CityStateZip) AS CityStateZip, max(v.EstimatedImprovementValue) AS EstimatedImprovementValue, max(v.OtherPartyName) AS OtherPartyName, max(v.OtherPartyMailingAddress) AS OtherPartyMailingAddress, max(v.OtherPartyCityStateZip) AS OtherPartyCityStateZip, max(v.ParcelNumber) AS ParcelNumber, max(v.PermitIssueTo) AS PermitIssueTo, max(v.PermitDescription) AS PermitDescription, max(v.CurrentPrimaryOwner) AS CurrentPrimaryOwnerFROM PermitCheckList AS p INNER JOIN vwPermit AS v ON p.PermitID = v.PermitIDWHERE (p.ApprovedDate BETWEEN @StartDate AND @EndDate)GROUP BY v.PermitNumberORDER BY v.PermitNumber;
Using row_number.with cte as(SELECT DISTINCT v.PermitNumber, p.ApprovedDate, v.ProcessStatus, v.PermitTypeDescription, v.ServiceAddress, v.CityStateZip, v.EstimatedImprovementValue, v.OtherPartyName, v.OtherPartyMailingAddress, v.OtherPartyCityStateZip, v.ParcelNumber, v.PermitIssueTo, v.PermitDescription, v.CurrentPrimaryOwner, ROW_NUMBER() OVER(PARTITION BY v.PermitNumber ORDER BY (SELECT NULL)) AS RNFROM PermitCheckList AS p INNER JOIN vwPermit AS v ON p.PermitID = v.PermitIDWHERE (p.ApprovedDate BETWEEN @StartDate AND @EndDate))SELECT * FROM CTE WHERE RN = 1;ORDER BY PermitNumber;
The values in other columns will have different logic in each of the methods. You have to decide what the right thing to do is in your situation.