简体   繁体   English

使用GROUP BY时,计算2列的不同值

[英]Count distinct values on 2 colums when using GROUP BY

Considering the following query: 考虑以下查询:

SELECT t.recording_id, m.release_id
FROM track t
JOIN medium m ON t.medium_id = m.medium_id

i get a result set similar to this one 我得到的结果与此相似

recording id    release id
----------------------------------
1               25
1               25
1               37
1               76
1               300
1               336
2               37
...             ...

i need to output the following 我需要输出以下内容

recording id    count
---------------------------------------------------
1              5
2              1

In other words, i need to group by the recording_id but not count the release_id duplicates for that recording_id 换句话说,我需要按recording_id分组,但不计算该recording_id的release_id重复项

After researching this board i've tried the following, with no success : 在研究此板后,我尝试了以下操作,但没有成功:

SELECT t.recording_id, count(t.recording_id)
FROM track t
JOIN medium m ON t.medium_id = m.medium_id
group by t.recording_id, m.release_id

but, im getting 但是,我越来越

recording id    release id
--------------------------
1              2
1              1
1              1
1              1
1              1
2              1

What's wrong? 怎么了?

Try this, you can use distinct in your count function to return distinct release ids for a recording_id 尝试此操作,您可以在count函数中使用distinct,以为recording_id返回独特的发行版id。

SELECT t.recording_id, count(distinct m.release_id) cnt
FROM track t
JOIN medium m ON t.medium_id = m.medium_id
group by t.recording_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM