I have a configuration table, that holds the values selected by a specific user. If no values where entered, then the default should be returned. But there’s a catch: the user belong to a speciffic group, and each group has it’s own defaul.
What I need is a single query that returns the user’s values, or the default for his/her group if no data found.
The config tables structure is quite simple:
CONFIGURATION: ConfigurationId (PK), GroupId (FK), UserId (FK), ConfigurationDetailId (FK);
CONFIGURATIONDETAIL: ConfigurationDetailId (PK), ConfigValue1, ConfigValue2
A user may belong to more than one group, and have different configurations for each. Those configs are considered different (have their own ConfigurationDetailId) even if their values are the same.
When I look for the data, I always have the GroupId and the UserId
This works, but I wanted something more “elegant”… What I don’t like is the TOP 1 and ORDER BY I need to eliminate the default row when a user specific row exists:
SELECT TOP 1
FROM Config C
WHERE C.GroupId = @GroupId
AND (C.UserId = @UserId OR C.UserId IS NULL)
ORDER BY C.UserId DESC
Any thoughts?
Perhaps try a self join, depending on your table structure.
Results for userid = 2
Results for userid = 1
I’ve built a SQLFiddle for this so you can see it for yourself.