Finding duplicate in SQL Server Table

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

I have a table

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


        
相关标签:
2条回答
  • 2021-01-29 13:18

    Supposing the data size is not so big, make a new temporay table joinning all data:

    Sales 
    Market
    

    then select grouping by Sales and after take the ones bigger than 1:

    select Max(Sales), Count(*) as Qty 
    from #temporary 
    group by Sales
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题