Understanding SQL Group By, Like a Boss...
The Oracle Documentation helps, but essentially the group by clause allows you to return one row for a column that might have duplicates. For instance if you groups all the member_ids in a post table together you could perfom some kind of calculation on them. How many there are, tally up a column for them, etc.
Group By Examples
How about we count the toal number of posts for users?
select MEMBER_ID, count(MEMBER_ID) from USER_POSTS group by MEMBER_ID;
MEMBER_ID COUNT(MEMBER_ID) ---------- --------------------------------------- 1404220137 14 1404782755 12 1414338077 13 1414369197 12
Ok now what if we want to total up the edits for each member?
select MEMBER_ID, count(EDIT_COUNT) from USER_POSTS group by MEMBER_ID;
MEMBER_ID COUNT(EDIT_COUNT) ---------- --------------------------------------- 1414481042 29 1414490498 21 1414490548 19 1414490340 2 1414490514 19 1414492023 3
Ok, cool. Getting the hang of it. How about the post with the most edits for each member?
select MEMBER_ID, max(EDIT_COUNT) from USERS_POSTS group by MEMBER_ID;
MEMBER_ID MAX(EDIT_COUNT) ---------- --------------------------------------- 1404081638 2 1404804526 0 1414390433 4 1414413987 10 1414358158 1 1414381507 6
Having Clause Examples
Now lets see how to add the HAVING clause into our statement. The where clause does not work in a group by function. So you can basically think of HAVING like a WHERE clause for your GROUP BY queires.
Let's only grab users who have actually editied a post.
select MEMBER_ID from USER_POSTS group by MEMBER_ID having sum(EDIT_COUNT) > 0;
MEMBER_ID ---------- 1405226398 1405263540 1405251685 1405216407