How to select data from single column in pairs from database?. Expected output is shown below as the id of employee1 is less than employee2. And these are grouped By Source "A". Thanks in advance.
Input: Employees Table
Expected Output Table:
I tried this
SELECT DISTINCT e1.employee_name AS employee1, e1.employee_name AS employee2, e2.employee_name
FROM Employees e1
LEFT JOIN Employees e2
ON e1.manager_id = e2.employee_id
GROUP BY e1.employee_name
ORDER BY e1.employee_id ASC;
But it gave me data in duplicates like below table which I don’t want.
2
Answers
Can you try this:
first you need to exclude the item itself on join e1.id < e2.id
second not to allow to have the same e1
then you will see that e2 is doubled again this is why i used
There you have a working example
First partition data with respect to
source
and then createrow_number
for every partition.Then separate data on
odd
&even
row_number
and join them with respect to same source and odd_table_rowNo = even_table_rowNo -1So, your data should be come as:
As, you filter out only
Source: A
data, so, need to add condition for that.Finally, MySQL query should be:
Output:
Sample Code: db<>fiddle