简体   繁体   English

如何对来自两个不同SQL语句的多个记录进行分组

[英]How to GROUP multiple records from two different SQL statements

I have a table called tbl which contains all the data I need. 我有一个名为tbl的表,其中包含我需要的所有数据。 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)*: 这是在tbl中存储数据的方式(注意 uID是char(20),cID是int)*:

uID cID uID cID

1 10 1 10

1 11 1 11

1 12 1 12

2 11 2 11

We usually query this table like 我们通常像这样查询该表

SELECT * FROM tbl WHERE uID = "1"

So it returns 所以它返回

uID cID uID cID

1 10 1 10

1 11 1 11

1 12 1 12

But I also need to return the row where uID is different but cID do match. 但是我还需要返回uID不同但cID匹配的行。 Or grab the uID of the second row (which is 2) based on cID and do a select statement like this: 或者,根据cID获取第二行的uID(即2),然后执行以下select语句:

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

That query will return what I'm looking for 该查询将返回我要查找的内容

uID cID uID cID

1 10 1 10

1 11 1 11

1 12 1 12

2 11 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. 该表包含很多行,我希望能够以编程方式针对cID匹配且uID不同的每个调用执行此操作。

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
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 SQL:在具有多个group by语句的两列上进行计算 - SQL: calculation on two columns with multiple group by statements 如何在一个SQL语句中比较来自不同数据库的两个值 - how to compare two values from different databases in one SQL statements 如何从与FK链接的两个不同表中删除记录? SQL - How to delete records from two different tables that are linked with FK? SQL 如何合并来自SQL Server中两个不同查询的记录的顺序 - How to merge order by records from two different queries in SQL Server SQL-带计数的多个分组依据语句 - SQL - Multiple Group By statements with counts SQL:如何根据另一个表中的记录从一个表中选择多个记录的计数? - SQL: How to select a count of multiple records from one table, based on records in a different table? 如何在 sql 中使用 group by 语句时检查多个条件 - how to check multiple condition while using group by statements in sql 如何在SQL中使用多个COUNT语句共享同一个GROUP BY? - How to use multiple COUNT statements in SQL sharing the same GROUP BY? SQL QUERY - 如何获取不同类型但来自同一父组的子记录 - SQL QUERY - how to get child records with different types but from the same parent group 如何使用sql从具有不同列的两个表中获取不同的记录 - How to get different records from two tables with different columns using sql
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM