SQL - 从A列中选择,对B列中的两个元素进行分组

时间:2016-07-01 16:28:49

标签: sql select

我有一个包含这样数据的SQL数据库:

A | B
-----
q | 1
w | 2
q | 2
w | 3
e | 1
e | 2
e | 3

我想看看A中具有相同值的不同行有多少次在B中有不同的值。那就是1和2的对用于q和e,所以我想要2.所以结果必须看像:

1, 2 | 2        (q and e have 1 and 2)
1, 3 | 1        (only e has both 1 and 3)
2, 3 | 2        (w and e have both 2 and 3)

我写了以下SELECT,但是错了:

SELECT DISTINCT d1.b AS b1, d2.b AS b2, COUNT(d1.a) 
FROM (SELECT a, b FROM data GROUP BY b) as d1, data as d2
GROUP BY b1, b2 
HAVING b1 <> b2

1 个答案:

答案 0 :(得分:0)

我认为您希望通过聚合进行自我加入:

我正在使用[A] = user [B] = event

<强> Demo

select d1.[event], d2.[event], count(distinct d1.[user]) num_user
from data d1 
join data d2
  on d1.[event] < d2.[event]
 and d1.[user] = d2.[user]   
group by d1.[event], d2.[event];

enter image description here