统计价值的独特组合

时间:2014-03-27 16:29:37

标签: sql sql-server

想象一下以下场景:

ColA | ColB
1    | 1
1    | 2
1    | 3
2    | 1
2    | 2
2    | 3
3    | 1
3    | 2
3    | 3

使用SQL Server 2008,我如何计算一个事件,使组合(1,2)与(2,1)相同,因此我的结果如下:

ColA | ColB | Count
1    | 1    | 1
1    | 2    | 2
1    | 3    | 2
2    | 2    | 1
2    | 3    | 2
3    | 3    | 1 

谢谢!

4 个答案:

答案 0 :(得分:1)

试试这个:

;with cte as
(select 
 ColA,
 ColB, 
 case when ColA < ColB then ColA else ColB end as ColC, 
 case when ColA > ColB then ColA else ColB end as ColD
from yourtable)
select 
ColC as ColA,
ColD as ColB,
count(1) as Count
from cte
group by ColC, ColD
order by ColC, ColD

答案 1 :(得分:1)

在分组之前,通过制作Col1 = MIN(Col1, Col2)Col2 = MAX(Col1, Col2)来规范化数据。这会将每种可能的组合转换为规范组合。然后,进行常规分组。

答案 2 :(得分:0)

示例已经发布在我之前,但我会发布无论如何。

将YourTable替换为您要查询数据的表格,以下解决方案将起作用。

它在WITH子句中将两组数据连接在一起,然后选择2列并进行计数。

WITH data as (
    select 
          ColA
         ,ColB
    from YourTable
union all
    select 
          ColA
         ,ColB
    from YourTable 
    where ColB <> ColA and ColA <> ColB
) 
select 
     ColA
    ,ColB
    ,count(*) as [Count]
from data
GROUP BY ColA,ColB

答案 3 :(得分:0)

这个怎么样:

select (case when colA < colB then colA else colB end) as ColA,
       (case when colA < colB then colB else colA end) as ColB,
       count(*)
from table t
group by (case when colA < colB then colA else colB end),
         (case when colA < colB then colB else colA end);

如果SQL Server支持greatest()least(),那么这看起来会更简单。但case语句同样适用。