Skip to content
Advertisement

Select rows by condition without groupby in SQL?

I have SQL table like below.

Type Code
1 11111
2 11111
1 22222
2 22222
1 33333
2 33333

And would like to get below result.

Type_1 Code_1 Type_2 Code_2
1 11111 2 11111
1 22222 2 22222
1 33333 2 33333

Please help.

Advertisement

Answer

It looks like you want to perform a self join. AKA, you want to join rows from a table to itself.

Here is a basic example using your sample data that will return what you want, just keep in mind there’s always more than one way to do things, and this particular way may not be the most efficient for wherever you plan to copy and use it:

SELECT s1.Type AS Type_1
    , s1.Code AS Code_1
    , s2.Type AS Type_2
    , s2.Code AS Code_2
FROM Sample s1
    JOIN Sample s2 ON s2.Code = s1.Code AND s2.Type = 2
WHERE s1.Type = 1;
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement