简体   繁体   中英

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?

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);

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
    )

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