everyone. I’m new here and I have a question on SQL which I seem to think that it may be easy to do in SQL but I’m out of ideas and I could use some help with my problem.
So I have a table (sql also here http://www.sqlfiddle.com/#!2/b9a37/1/0)
With multiple occurences for each person, different id’s with auto increment and I have 3 fields, “Category”, “In” and “Out”
What I’m trying to implement is a way for me to know when some of the users on the table belongs to the system using the “In” and “Out” as the limits.
Example
- User A – Category A – IN 2002 OUT 2010
- User A – Category B – IN 2011 OUT 9999
- User B – Category B – IN 2002 OUT 2010
In the above example I would like to know who belongs to the system in year 2010:
so for User A, he Left Category A in 2010 but joined in 2011 Category 2011 so he SHOULD be a user in 2010 with Category A
for User B he should NOT belong to the system because there’s no new entry for 2010+
At the end I’m tring to have the following output for 2010
- Smith Category A
- Pablo Category A
I’m not achieving the results I want, for example
SELECT * from users
WHERE (users.In<=2010 and users.Out=2010)
Outputs
- Smith Category A In 2002 Out 2010
- Roger Category B In 2002 Out 2010
- Miller Category B In 2008 Out 2010
- Pablo Category A In 2002 Out 2010
But Roger and Miller left the system in 2010 so they should NOT be members in 2010, and Smith and Pablo changed their category in 2010+ so they should show in the output.
A few notes:
Don’t ask me why this solution is developed like this, I just stumbled on it and trying to solve this issue.
I’m considering doing a function in php do filter the data based on the requirements that I want because i’m running out of ideas to solve this.
If you find a way to implement this better than what I saw here, be my guest and i’m open to new ideas.
Thanks in advance.
Final Note:
Perhaps using http://www.sqlfiddle.com/#!2/b9a37/1/0 and try to find the desired output will help you out.
Give this one a shot:
SQL Fiddle Example