如何在多个条件下找出相同的值并将同一列的值放在不同的列中?

How can I find out same values with more than one condition and put values of the same column in different columns?

我必须找出哪对国家/地区在同一日期和同一卖家的销售额相同。然后我想订购它,例如同一列中的两个国家在不同的列中彼此相邻,以及日期、卖家和销售数量。

我有一个 table countries 这样的:

Country_code Country_name
1 Argentina
2 Brazil
3 Peru
4 Bolivia

我有一个(缩短的)table sales 像这样:

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

所以,在这种情况下,我的预期结果应该是:

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

我已经设法 select 获得了正确的数据,但我没能将国家/地区分为两个不同的列。

这是我的代码:

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

提前致谢!

好的。这是一个建议的解决方案,考虑到只有成对的国家是 expected/required 并且只显示两个国家名称列。通过在分组中使用最小值和最大值,将仅选择这两个国家/地区。
(如果恰好有两个以上国家的日期相同,seller,no_of_sales那么中间的将被忽略。)

SELECT distinct s1.Date
,c1.country_name Country_name_1
,c2.country_name Country_name_2
,s1.Seller, s1.No_of_sales 
FROM (sales s1
INNER JOIN
(SELECT min(country_code) country1, max(country_code) country2, 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 c1
ON s2.country1 = c1.Country_code
JOIN countries c2
ON s2.country2 = c2.Country_code

其他解决方案,但与 Catherine 提供的解决方案相比要复杂得多

            with flo as (
            select *,  row_number()over(order by (select 1)) -row_number()over(partition by date, no_of_sales, seller order by (select 1)) as rn
            from sales), 
            flo1 as (
            select country_code, date, no_of_sales, seller from (
            select country_code, date, no_of_sales, seller, rn ,lead(rn)over(order by rn) as ln
            from flo ) a
            where ln-rn=0 or ln-rn=2
            ) ,
            flo2 as (select a.date, b.country_name, b.country_name as bcountry_name, a.no_of_sales, a.seller
            from flo1 a join countries b on  a.country_code=b.country_code
            ), 
            flo3 as (select *, row_number()over(partition by date, no_of_sales, seller order by country_name)as rn 
            from flo2)
            select date, max(case when rn=1 then country_name end) as country_name, 
            max(case when rn=2 then bcountry_name end) as bcountryname, no_of_sales, seller
            from flo3 
            group by no_of_sales, seller, date
            order by 1