Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select rows with duplicate values in 2 columns

This is my table:

CREATE TABLE [Test].[dbo].[MyTest]
(
[Id]    BIGINT NOT NULL,
[FId]   BIGINT NOT NULL,
[SId]   BIGINT NOT NULL
);

And some data:

INSERT INTO  [Test].[dbo].[MyTest] ([Id], [FId], [SId]) VALUES (1, 100, 11); 
INSERT INTO  [Test].[dbo].[MyTest] ([Id], [FId], [SId]) VALUES (2, 200, 12); 
INSERT INTO  [Test].[dbo].[MyTest] ([Id], [FId], [SId]) VALUES (3, 100, 21); 
INSERT INTO  [Test].[dbo].[MyTest] ([Id], [FId], [SId]) VALUES (4, 200, 22);
INSERT INTO  [Test].[dbo].[MyTest] ([Id], [FId], [SId]) VALUES (5, 300, 13); 
INSERT INTO  [Test].[dbo].[MyTest] ([Id], [FId], [SId]) VALUES (6, 200, 12); 

So I need 2 select query,

First Select FId, SId that like a distinct in both column so the result is:

100, 11
200, 12
100, 21
200, 22
300, 13

As you see the values of 200, 12 returned once.

Second query is the Id's of that columns whose duplicated in both FId, SId So the result is:

2
6

Does any one have any idea about it?

like image 446
Saeid Avatar asked Feb 16 '26 13:02

Saeid


1 Answers

Standard SQL

SELECT
    M.ID
FROM
    ( -- note all duplicate FID, SID pairs
    SELECT FID, SID
    FROM MyTable
    GROUP BY FID, SID
    HAVING COUNT(*) > 1
    ) T
    JOIN -- back onto main table using these duplicate FID, SID pairs
    MyTable M ON T.FID = M.FID AND T.SID = M.SID

Using windowing:

SELECT 
    T.ID
FROM
    (
    SELECT
        ID,
        COUNT(*) OVER (PARTITION BY FID, SID) AS CountPerPair
    FROM
        MyTable
    ) T
WHERE
   T.CountPerPair > 1
like image 171
gbn Avatar answered Feb 19 '26 09:02

gbn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!