0

I'm trying to write a query to return all columns, and filter by displaying DISTINCT records from a specific column.

Here is my Query right now, which requires me to "Group By" everything in the select statement. I obviously don't want to do this.:

SELECT     lVisitID, sFirstName, sLastName, sAddress1, sStoreNumber
FROM        Customers
WHERE     (dtServiceDate < '5/1/15') AND (sStoreNumber = '123') 
GROUP BY sAddress1

I've also tried the below, but that returns duplicates:

    SELECT     lVisitID, MAX(sAddress1)
    FROM        Customers
    WHERE     (dtServiceDate < '5/1/15') AND (sStoreNumber = '123') 
    GROUP BY sAddress1, lvisitID

Here is my data:

lVisitID     sFirstName   sLastName     sAddress1     sStoreNumber
  1             Bob          Jones         14 Place     123
  2             Jim          Bibby         12 Place     123
  3             John         Smith         12 Place     123
  4             Jen         Jones          22 Place     193
  6             Kim         Smith          15 Place     123

The idea here would be to return Only distinct addresses, and the store number. When I attempt the above, I need:

  1             Bob          Jones         14 Place     123
  2             Jim          Bibby         12 Place     123
  6             Kim         Smith          15 Place     123
1
  • Please tag your question with the database you are using. Commented Jul 9, 2015 at 2:30

2 Answers 2

3

If you want just the address that has the most recent visit, use row_number():

select c.*
from (select c.*,
             row_number() over (partition by address order by lVisitId desc) as seqnum
      from customers c
     ) c
where seqnum = 1;
Sign up to request clarification or add additional context in comments.

Comments

1

I tried this on Postgres SQL.

SELECT     Distinct on (sAddress1) *
FROM        Customers
WHERE     (dtServiceDate < '5/1/15') AND (sStoreNumber = '123') 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.