smr5
smr5

Reputation: 2793

How to GROUP multiple records from two different SQL statements

I have a table called tbl which contains all the data I need. I have many columns in this table, but for purposes of this example I will only list the columns necessary to accomplish this task.

Here's how data stored in the tbl (note uID is char(20) and cID is int)*:

uID cID

1 10

1 11

1 12

2 11

We usually query this table like

SELECT * FROM tbl WHERE uID = "1"

So it returns

uID cID

1 10

1 11

1 12

But I also need to return the row where uID is different but cID do match. Or grab the uID of the second row (which is 2) based on cID and do a select statement like this:

SELECT * FROM tbl WHERE uID in ('1','2')

That query will return what I'm looking for

uID cID

1 10

1 11

1 12

2 11

This table contains a lot of rows and I want to be able to do this programatically for every call where cID matches and uID is different.

Any suggestions?

Upvotes: 0

Views: 66

Answers (2)

InitK
InitK

Reputation: 1281

or something like this:

SELECT uID, cID
FROM tbl 
WHERE uID IN 
    (
        SELECT uID
        FROM tbl
        INNER JOIN 
            (
                SELECT cID
                FROM tbl
                GROUP BY cID
                HAVING count(*) > 1
            ) c ON c.cID = tbl.cID
    )

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1269883

I think this may be what you want:

SELECT *
FROM tbl
WHERE uID = '1'
UNION ALL
SELECT *
FROM tbl
WHERE uID <> '1' AND
      EXISTS (select 1 from tbl tbl2 where tbl2.uId = '1' and tbl2.cID = tbl.cID);

Upvotes: 2

Related Questions