对具有相同等效值的行进行分组

时间:2016-10-13 04:07:20

标签: sql sql-server sql-server-2008

我将下一个样本数据放入表格(EQUCODES),列#34; CODE"具有等价值,表示为" EQCODE"柱。这个值在" EQCODE"列可以是" CODE"中具有相同值的另一个记录。列和等效值将具有相反的值,即

ID  || CODE || EQCODE  
--------------------------
1   ||  a   || b   
2   ||  b   || a   
3   ||  c   || d   
4   ||  d   || c   

我要与上表联接的其他表(CLIENTTYPE)具有下一个estructure,

CLIENTID  || CODE   
--------------------------
1         ||  a  
2         ||  a    
3         ||  b   
4         ||  a   
6         ||  b   
7         ||  b   

如何以查询返回单个记录的方式对这些CLIENTTYPE记录进行分组,因为它们在与EQUCODES表连接后是等效的?

1 个答案:

答案 0 :(得分:0)

要查找每个客户端的规范代码,请使用以下命令:

select ClientID, min(code) as Code
from (
    select ClientID, EQUCODES.EQCode as Code
    from CLIENTTYPE inner join EQUCODES on CLIENTTYPE.Code = EQUCODES.Code
  Union
    select ClientID, EQUCODES.Code
    from CLIENTTYPE inner join EQUCODES on CLIENTTYPE.Code = EQUCODES.EQCode
) U
Group By ClientID

如果您希望按code聚合,可以将该查询包装在此:

select Code, count(ClientID) from
( -- the query above
) G
Group by Code