I have the following data in the table (I’m using SQL Server 2008R2):
Customer Code, Device Expiry Date, Device Name, Log ID
S001, NULL, Dvc A, 1
S002, NULL, Dvc B, 2
S002, NULL, Dvc A, 3
S003, 2010-01-01, Dvc A, 4
S004, 2011-06-25, Dvc B, 5
S004, 2012-02-10, Dvc A, 5
Log ID column is based on running number.
I want to select one record for each customer code based on the following criteria:
– If Device Expiry Date is not null then take the record with the latest date
– If all the expiry date is null then take the latest record (maximum log ID)
Hence, the selected records will be:
Customer Code, Device Expiry Date, Device Name, Log ID
S001, NULL, Dvc A, 1
S002, NULL, Dvc A, 3
S003, 2010-01-01, Dvc A, 4
S004, 2012-02-10, Dvc A, 5
The output of the query will be further joined with master customer code:
Customer Code, Member Type
S001, Silver
S002, Gold
S003, Silver
S004, Silver
S005, Gold
When joined, the end result will be:
Customer Code, Member Type, Device Expiry Date, Device Code
S001, Silver, NULL, Dvc A
S002, Gold, NULL, Dvc A
S003, Silver, 2010-01-01, Dvc A
S004, Silver, 2012-02-10, Dvc A
S005, Gold, NULL, NULL
What I had on mind is to use several sub queries just to get the Devices records. Please help with some idea on getting the above result. Thank you in advance.
You could try the following (untested)
The idea is to add a rownumber to each row that will
Log IDNULLdateAll that’s required now is to select all records from the resultset where this rownumber = 1.