Finding duplicate in SQL Server Table

此生再无相见时 提交于 2019-12-04 07:05:42

问题


I have a table

+--------+--------+--------+--------+--------+
| Market | Sales1 | Sales2 | Sales3 | Sales4 |
+--------+--------+--------+--------+--------+
|     68 |      1 |      2 |      3 |      4 |
|    630 |      5 |      3 |      7 |      8 |
|    190 |      9 |     10 |     11 |     12 |
+--------+--------+--------+--------+--------+

I want to find duplicates between all the above sales fields. In above example markets 68 and 630 have a duplicate Sales value that is 3.

My problem is displaying the Market having duplicate sales.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/23919876/finding-duplicate-in-sql-server-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!