Finding duplicate in SQL Server Table

后端 未结 2 1238
天命终不由人
天命终不由人 2021-01-29 13:03

I have a table

+--------+--------+--------+--------+--------+
| Market | Sales1 | Sales2 | Sales3 | Sales4 |
+--------+--------+--------+--------+--------+
|            


        
2条回答
  •  执笔经年
    2021-01-29 13:31

    This problem would be incredibly simple to solve if you normalised your table.

    Then you would just have the columns Market | Sales, or if the 1, 2, 3, 4 are important you could have Market | Quarter | Sales (or some other relevant column name).

    Given that your table isn't in this format, you could use a CTE to make it so and then select from it, e.g.

    WITH cte AS (
        SELECT Market, Sales1 AS Sales FROM MarketSales
        UNION ALL 
        SELECT Market, Sales2 FROM MarketSales
        UNION ALL 
        SELECT Market, Sales3 FROM MarketSales
        UNION ALL 
        SELECT Market, Sales2 FROM MarketSales
    )
    SELECT a.Market
          ,b.Market
    FROM cte a
    INNER JOIN cte b ON b.Market > a.Market
    WHERE a.Sales = b.Sales
    

    You can easily do this without the CTE, you just need a big where clause comparing all the combinations of Sales columns.

提交回复
热议问题