[英]How to Combine DISTINCT and COUNT the aggregated Values
I have a table with subjects with the columns capture_group_id, subject_id, and round_id and some other columns. 我有一张表,其中的主题包含capture_group_id,subject_id和round_id列以及其他一些列。 I want to write a SELECT statement which returns the distinct subjects without paying regard to the round_id, but i want also to know in how many rounds the Subject participated.
我想编写一个SELECT语句,该语句返回不同的主题,而无需考虑round_id,但是我也想知道主题参与了多少回合。
I've come to these two Solutions (which aren't returning the result in the needed form) 我来了这两个解决方案(未以所需的形式返回结果)
FIRST: 第一:
SELECT study_case.capture_group_id, proband.subject_id,Count(1) AS Count
FROM study_case
JOIN proband
ON study_case.proband_id = proband.proband_id
GROUP BY study_case.capture_group_id, proband.subject_id
this returns the distinct subjects with the count of participated rounds. 这将返回参与回合计数的不同主题。 But i can't add columns to the select statement whicht aren't included in the group by statement.
但是我不能将列不添加到选择语句中的列中。
Another approach was: 另一种方法是:
SELECT DISTINCT ON (study_case.capture_group_id, proband.subject_id) study_case.capture_group_id, proband.subject_id, study_case.round_id, proband.gender, proband.birth_year, proband.birth_country
FROM study_case
JOIN proband
ON study_case.proband_id = proband.proband_id
ORDER BY study_case.capture_group_id, proband.subject_id, study_case.round_id
How can I build a SQL Statment which shows the distinct subjects, counts the DISTINCT aggregated Subjects and includes all columns from the second statement? 如何建立一个显示不同主题,对DISTINCT聚合主题进行计数并包括第二条语句中所有列的SQL语句?
You can do what you want with window functions: 您可以使用窗口功能执行所需的操作:
SELECT capture_group_id, subject_id, round_id, gender, birth_year, birth_country, cnt
FROM (SELECT sc.capture_group_id, p.subject_id, sc.round_id, p.gender,
p.birth_year, p.birth_country,
row_number() over (partition by study_case.capture_group_id, p.subject_id
order by sc.capture_group_id, p.subject_id, sc.round_id
) as seqnum,
count(*) over (partition by sc.capture_group_id, p.subject_id) as cnt
FROM study_case sc JOIN
proband p
ON sc.proband_id = p.proband_id
) t
WHERE seqnum = 1
ORDER BY capture_group_id, subject_id, round_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.