We have a database with duplicate user entries, and I need to choose the "best" user based on several factors:
- Members with membership must be selected before those with
- Members have levels, and ceteris paribus, the user must choose the "best" level of membership.
- Users with active membership must be selected in front of users with expired membership.
Based on these conditions, I came up with something like the following query (the current query is too sensitive).
SELECT TOP 1 u.[UserId]
FROM [dbo].[Users] u
LEFT OUTER JOIN [dbo].[UserMemberships] um
ON u.[UserId] = um.[UserId]
LEFT OUTER JOIN [dbo].[Memberships] m
ON um.[MembershipId] = m.[MembershipId]
WHERE u.[Email] = @Email
ORDER BY m.[Order] ASC, um.[Expires] DESC, u.[Created] DESC
, , . , , "" ( ), , , , . , , ( ) .
, , , , . , ?