SQL Server SQL Query to select duplicates without grouping [duplicate]

wz1wpwve  于 2024-01-05  发布在  其他
关注(0)|答案(2)|浏览(131)

This question already has answers here:

SELECT Full Row with Duplicated Data in One Column (4 answers)
Check which all records have duplicate using window function (1 answer)

Closed last month.

I want to find rows in my table where both power and price match some other row in the table.

  1. +----+-------+-------+--------+
  2. | id | Power | Price | Name |
  3. +------------+-------+--------+
  4. | 1 | 300W | $5.00 | Alpha |
  5. | 2 | 500W | $4.00 | Kilo |
  6. | 3 | 500W | $3.00 | Whiskey|
  7. | 4 | 300W | $5.00 | Charlie|
  8. | 5 | 400W | $4.00 | Oscar |
  9. +----+-------+-------+--------+

I want the resulting table to include all columns, including the primary key, and I don't want them grouped.

  1. +----+-------+-------+--------+
  2. | id | Power | Price | Name |
  3. +------------+-------+--------+
  4. | 1 | 300W | $5.00 | Alpha |
  5. | 4 | 300W | $5.00 | Charlie|
  6. +----+-------+-------+--------+

What can I do to find duplicates without any of the columns or duplicate rows being eliminated?

2w3rbyxf

2w3rbyxf1#

If your RDBMS support window functions, you can use function COUNT() , then select only the records having count higher than 1 :

  1. select id, Power, Price, Name
  2. from (
  3. select *, count(*) over (partition by Power, Price) as cnt
  4. from mytable
  5. ) as s
  6. where cnt > 1;

Demo here

kkih6yb8

kkih6yb82#

Basic doubloon search :

  1. SELECT *
  2. FROM mytable t1
  3. WHERE EXISTS (
  4. SELECT *
  5. FROM mytable t2
  6. WHERE t1.id <> t2.id
  7. AND t1.Power = t2.Power
  8. AND t1.Price = t2.Price
  9. );

相关问题