I have to find out in which pair of countries is the same number of sales at the same date and the same seller. Then I want to order it such as there are the two countries from the same column next to each other in separate columns, as well as date, the seller and the number of sales.
I have a table countries like this:
| Country_code | Country_name |
|---|---|
| 1 | Argentina |
| 2 | Brazil |
| 3 | Peru |
| 4 | Bolivia |
And I have a (shortened) table sales like this:
| Country_code | Date | No_of_sales | Seller |
|---|---|---|---|
| 1 | 2021-01-01 | 17 | D |
| 2 | 2021-01-01 | 48 | K |
| 3 | 2021-01-01 | 19 | X |
| 4 | 2021-01-01 | 22 | Z |
| 1 | 2021-02-01 | 66 | D |
| 2 | 2021-02-01 | 66 | D |
| 3 | 2021-02-01 | 87 | K |
| 4 | 2021-02-01 | 10 | K |
| 1 | 2021-03-01 | 27 | Z |
| 2 | 2021-03-01 | 17 | D |
| 3 | 2021-03-01 | 17 | D |
| 4 | 2021-03-01 | 32 | D |
So, in this case, my expected result should be:
| Date | Country_name_1 | Country_name_2 | Seller | No_of_sales |
|---|---|---|---|---|
| 2021-02-01 | Argentina | Brazil | D | 66 |
| 2021-03-01 | Brazil | Peru | D | 17 |
I already managed it to select the correct data, but I didn't manage to separate the countries in two different columns.
This is my code:
SELECT s1.date, c.country_name, s1.seller, s1.No_of_sales
FROM (sales s1
INNER JOIN
(SELECT seller, date, No_of_sales FROM sales
GROUP BY seller, date, No_of_sales
HAVING COUNT(seller) > 1) s2
ON s1.seller = s2.seller AND s1.date = s2.date AND s1.No_of_sales = s2.No_of_sales)
JOIN countries c
ON s1.Country_code = c.Country_code
Thank you in advance!