Select 列值在多列分组时出现多次的行

Select rows where column value appears multiple times while grouped on multiple columns

我想按两列分组,ClientID, TypeID 和 select ClientID 值在 table 中出现不止一次的所有行。因此,不仅仅是这些值的列表,而是所有行。

例如,这是我的内部子查询结果:

╔══════════╦════════╦══════════╗
║ ClientID ║ TypeID ║ Count(*) ║
╠══════════╬════════╬══════════╣
║ "0"      ║ "1"    ║ "1"      ║
╠══════════╬════════╬══════════╣
║ "455"    ║ "1"    ║ "1"      ║
╠══════════╬════════╬══════════╣
║ "455"    ║ "2"    ║ "1"      ║
╠══════════╬════════╬══════════╣
║ "455"    ║ "8"    ║ "1"      ║
╠══════════╬════════╬══════════╣
║ "40036"  ║ "8"    ║ "1"      ║
╠══════════╬════════╬══════════╣
║ "40070"  ║ "7"    ║ "1"      ║
╠══════════╬════════╬══════════╣
║ "40070"  ║ "8"    ║ "1"      ║
╠══════════╬════════╬══════════╣
║ "40082"  ║ "2"    ║ "1"      ║
╠══════════╬════════╬══════════╣
║ "40082"  ║ "12"   ║ "1"      ║
╠══════════╬════════╬══════════╣
║ "40085"  ║ "1"    ║ "1"      ║
╚══════════╩════════╩══════════╝

我想要这个输出:

╔══════════╦════════╦══════════╗
║ ClientID ║ TypeID ║ Count(*) ║
╠══════════╬════════╬══════════╣
║ "455"    ║ "1"    ║ "1"      ║
╠══════════╬════════╬══════════╣
║ "455"    ║ "2"    ║ "1"      ║
╠══════════╬════════╬══════════╣
║ "455"    ║ "8"    ║ "1"      ║
╠══════════╬════════╬══════════╣
║ "40070"  ║ "7"    ║ "1"      ║
╠══════════╬════════╬══════════╣
║ "40070"  ║ "8"    ║ "1"      ║
╠══════════╬════════╬══════════╣
║ "40082"  ║ "2"    ║ "1"      ║
╠══════════╬════════╬══════════╣
║ "40082"  ║ "12"   ║ "1"      ║
╚══════════╩════════╩══════════╝

可以看到完全一样,只是ClientID值没有出现超过一次的行没有了。

这是我的 MySQL 查询,但是这自然会给我一个空结果,因为所有行都是唯一的,所以 Count(*) 列永远不会超过 1,这与按 a 分组不同在这种情况下,单个字段而不是两个字段。

SELECT *, COUNT(*) AS C
FROM (
    SELECT ClientID, TypeID
    FROM table
    GROUP BY ClientID, TypeID
) AS R
GROUP BY ClientID, TypeID
HAVING COUNT(C) > 1
ORDER BY ClientID, TypeID

我应该如何计算聚合两列的组,以便 Count(*) 字段实际包含正确的出现次数?

您可以使用 existsdistinct:

select distinct clientID, typeID
from mytable t
where exists (
    select 1 from mytable t1 where t1.clientID = t.clientID and t1.typeID <> t.typeID
)

或者如果您还需要计数,请使用聚合而不是 distinct:

select clientID, typeID, count(*) cnt
from mytable t
where exists (
    select 1 from mytable t1 where t1.clientID = t.clientID and t1.typeID <> t.typeID
)
group by clientID, typeID

为了提高性能,请考虑 (clientID, typeID) 上的索引。

select t.*,
(select count(*)from table i where i.ClientID=t.ClientID and i.TypeID=t.TypeID) as Count 
from table t where clientID in (
select ClientID from table
GROUP BY ClientID
HAVING COUNT(ClientID) > 1)