计算来自同一列的差异组合的出现?

时间:2016-10-19 17:22:50

标签: sql count google-bigquery

我想算一下参加2门课程组合的人数

假设我有一个table1:

Name    course
-----------------
Mary    Biology
Mary    Chemistry
Mary    Music
Kim     Music
Kim     Chemistry
Kim     Mathematics
Ida     Mathematics
Ida     Biology
Ida     Music

结果应该是这样的

Biology   Chemistry   1
Biology   music       2
Chemistry music       2
Mathematics music     2

这是我得到的,但是没有用。

select * From (
select t1.course, t2.course, count (*) AS total from 
(select
t1.name t1.course, t2.course
from data t1
JOIN data t2 ON t1.name=t2.name
where t1.course<>t2.course)
group by t1.name,t1.course,t2.course)
order by total desc; 

2 个答案:

答案 0 :(得分:1)

用于BigQuery Legacy SQL或BigQuery Standard SQL(请参阅Enabling Standard SQL

SELECT 
  a.course as course_a, 
  b.course as course_b, 
  COUNT(*) as cnt
FROM rekry_data a 
JOIN rekry_data b 
ON a.Name=b.Name
WHERE a.course < b.course
GROUP BY a.course, b.course

答案 1 :(得分:0)

SELECT a.course, b.course, COUNT(*)
FROM mytable a JOIN mytable b ON a.Name=b.Name AND a.Course <> b.Course 
GROUP BY a.course, b.course