Skip to content
Advertisement

Self Joining between 2 same tables

For instance I have a table called employees where it consists of “Employee ID”, “First Name”, “Last Name”, “Manager ID”. To count the subordinate of each manager, I tried to self-joining between the 2 tables.

Am I right? Also, if I want to join with other tables after self-joining, is the joining statement right?

Combining the first and last name:

I can’t compile this….What is wrong?

Advertisement

Answer

An answer for your first question is just a minor tweak to your query:

I really haven’t changed much here – and you can see that it works at: http://sqlfiddle.com/#!9/187477/1

The essential change is sticking with the names coming from the same table reference (e1) and GROUPing BY the same fields. You also need to (as commented) indicate the table name before aliasing with “e2”.

(Note that the aliasing of the names is just to help indicate that these are managers, it’s not an essential part of the query. Also, I used slightly different field names, but the logic is the same.)

As to your second question, I’d do it using the self-join query as a sub-query, more or less as you suggest. Try something out – you’re essentially at a solution.

EDIT IN RESPONSE TO QUESTION EDIT:

Adding the concatenation in (note that oracle has some limits around concatenating more than 2 strings, so this is one possible workaround – there’s more info at this answer: Oracle SQL, concatenate multiple columns + add text):

still works: http://sqlfiddle.com/#!4/b0cbcd/4

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement