5

I need to get the earliest Created Date with group by identity number. Here the sample of record.

| AccountID | DisplayName | CreatedDate | IdentityNumber | OrganizationID | |-----------|---------------|-------------|----------------|----------------| | 1 | John | 1 Jan 2018 | 1234 | 1000 | | 2 | John | 15 Jan 2018 | 1234 | 1001 | | 3 | John | 20 Jan 2018 | 1234 | 1002 | | 4 | Michael | 1 Jan 2018 | 1235 | 1000 | | 5 | Michael | 3 Jan 2018 | 1235 | 1003 | | 6 | Wood | 2 Jan 2018 | 1236 | 1002 | 

So I want to produce the result like this.

| AccountID | DisplayName | CreatedDate | IdentityNumber | OrganizationID | |-----------|---------------|-------------|----------------|----------------| | 1 | John | 1 Jan 2018 | 1234 | 1000 | | 4 | Michael | 1 Jan 2018 | 1235 | 1000 | | 6 | Wood | 2 Jan 2018 | 1236 | 1002 | 

This my sql snippet

SELECT IdentityNumber, MIN(CreatedDate) FROM Accounts GROUP BY IdentityNumber 

And yes I can get the earliest record with group by identity number. But how I can grab the AccountID, DisplayName, OrganizationID without group by?

3 Answers 3

5

Another option is using the WITH TIES clause in concert with Row_Number()

Select Top 1 with ties * From dbo.Accounts Order By Row_Number() over (Partition By IdentityNumber Order By CreatedDate) 
Sign up to request clarification or add additional context in comments.

2 Comments

@Chuki2 Yup. Tha'ts me in 4 words :)
what a much nicer way of doing it without a subselect.
0

You can use ROW_NUMBER:

;WITH CTE AS ( SELECT *, RN = ROW_NUMBER() OVER( PARTITION BY IdentityNumber ORDER BY CreatedDate) FROM dbo.Accounts ) SELECT AccountID, DisplayName, CreatedDate, IdentityNumber, OrganizationID FROM CTE WHERE RN = 1; 

Comments

0

Use the MIN keyword

SELECT DISTINCT [AccountID],[DisplayName],MIN([CreatedDate]),[IdentityNumber],[OrganizationID] FROM dbo.[Accounts] GROUP BY [IdentityNumber] 

the above code will return

AccountID DisplayName CreatedDate IdentityNumber OrganizationID
1 John 1 Jan 2018 1234 1000
4 Michael 1 Jan 2018 1235 1000
6 Wood 2 Jan 2018 1236 1002

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.