在多个组中查找唯一数量的id

bfhwhh0e  于 2021-07-26  发布在  Java
关注(0)|答案(4)|浏览(381)

我有一个数据集,里面有医生和他们从事的各种业务。在我的数据集中,每个医生至少有一个诊所,但多达17个不同的做法。我想知道每个人都有多少医生。当前的数据集在sas中,但我熟悉python、pandas和sql。我很好转换成任何格式的数据需要这样的答案不需要在sas代码。
示例数据集如下。此示例显示医生a正在实践中,p1、p3和p5。医生e从事实践p1、p2和p5等。

从这个图表中,我想要一个新的列,列有每个人都与之合作的唯一医生的总数。在本例中,医生a和其他2个医生(e&d)一起工作。然而,如果我简单地按医生分组并求和,我发现医生a和6个医生一起工作。但是这是错误的,因为它将计算医生a 3次(他所列的每种做法一次)和医生e两次(他与医生a、p1和p5在两组做法中)
我有大约80万名医生,有大约40万个团体练习,使得手工方法不可行。有人对如何开始这项工作有什么建议吗?
最终输出如下:

样本数据集代码(用于sas)

  1. input doctor $ tot_in_group group_practices $;
  2. datalines;
  3. A 2 P1
  4. E 2 P1
  5. C 3 P2
  6. B 3 P2
  7. E 3 P2
  8. A 2 P3
  9. D 2 P3
  10. E 2 P5
  11. A 2 P5
  12. ;
  13. run;
kognpnkq

kognpnkq1#

不包括自配对的组内的自联接将为每个组生成一个包含所有配对的表。将这个概念作为计算所有组中每个医生的不同“伴侣”的基础。
为了真正的独特性,请确保您使用的是 doctorId 对每个人都不同。试图阻止基于名字的“自我配对”是自找麻烦(设想一个虚构的群体,有杜威医生,杜威,杜威,杜威和杜威——是的,麻烦)

  1. data have;
  2. input doctor $ group $;
  3. datalines;
  4. A P1
  5. E P1
  6. C P2
  7. B P2
  8. E P2
  9. A P3
  10. D P3
  11. E P3
  12. E P5
  13. A P5
  14. ;
  15. run;
  16. proc sql;
  17. * demonstrate the combinatoric effect of who (P) paired with whom (Q) within group;
  18. * do not submit against the big data;
  19. create table works_with_each as
  20. select
  21. P.doctor as P
  22. , Q.doctor as Q
  23. , P.group
  24. from have as P
  25. join have as Q
  26. on P.group = Q.group
  27. & P.doctor ^= Q.doctor
  28. order by
  29. P.doctor, Q.doctor, P.group
  30. ;
  31. * count the distinct pairing, regardless of group;
  32. create table works_with_counts as
  33. select
  34. P.doctor as P
  35. , count(distinct Q.doctor) as unique_work_with_count
  36. from have as P
  37. join have as Q
  38. on P.group = Q.group
  39. & P.doctor ^= Q.doctor
  40. group by
  41. P.doctor
  42. order by
  43. P.doctor
  44. ;

每个

独特的其他成对(工作)计数

展开查看全部
5n0oy7gb

5n0oy7gb2#

您可能需要用您的语言(尤其是 COUNT(DISTINCT var) )

  1. SELECT docA , COUNT(DISTINCT docB) FROM
  2. (SELECT A.doctor as docA, B.doctor as docB FROM mytable A JOIN mytable B
  3. ON A.group_practices = B.group_practices WHERE A.doctor > B.doctor)
  4. GROUP BY docA

然后可以将此表与前面显示的表联接起来 on doctor = docA 这个 docA>docB 防止: A in relation with A ,
或者像这样的复制品 A in relation in B 以及 B in relation with A

idfiyjo8

idfiyjo83#

您可以自行加入并聚合:

  1. select t.doctor, count(distinct t1.doctor) no_coworkers
  2. from mytable t
  3. inner join mytable t1 on t1.doctor <> t.doctor and t1.group_practices = t.group_practices
  4. group by t.doctor
hivapdat

hivapdat4#

在数据库中,可以使用窗口函数:

  1. select t.*, count(*) over (partition by practice) as cnt
  2. from t;

procsql不支持这个。相反,您可以在sas中使用一个称为“重新融合”的奇怪功能:

  1. select t.*, count(*) as num_in_practice
  2. from t
  3. group by practice;

如果您对数据库使用本机格式,那么请使用window函数!

相关问题