简体   繁体   中英

SQL command for distinct values in one column and multiple same values in another

My table have the following kind of entries:

Serial Number | Cycle Number

55                33

56                27

55                34

55                33

57                5

57                6

56                28

57                6

I would like to return distinct Serial Numbers that have multiple Cycle Numbers with the same value

Serial Number |  Cycle Number

55                33

55                33

57                6

57                6 

Any help would be appreciated.

You can use the following query that will return the distinct Serial Number which have the multiple Cycle Number with same value.

SELECT SerialNumber, CycleNumber
FROM Table
GROUP BY SerialNumber, CycleNumber HAVING COUNT(SerialNumber)>1

If you really only have two columns, you could do:

select serial, cycle
from t
where (serial, cycle) in (select serial, cycle
                          from t t2
                          group by serial, cycle
                          having count(*) >= 2
                         );

But why wouldn't you just do this?

select serial, cycle, count(*)
from t
group by serial, cycle;

SQL Syntax:

SELECT A.* FROM tmpTable A
LEFT JOIN
( 
SELECT SerialNumber,CycleNumber FROM tmpTable  GROUP BY  SerialNumber, CycleNumber having count(SerialNumber)>1
) B ON A.SerialNumber = B.SerialNumber And A.CycleNumber = B.CycleNumber
WHERE B.SerialNumber is not null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM