简体   繁体   English

计算和划分SQL中多个列的不同值对

[英]Count and divide distinct value pairs from multiple columns in SQL

I'm new to SQL and having trouble looking for a query that can produce the last output table. 我是SQL的新手,很难找到可以产生最后一个输出表的查询。

Example table of what I have: 我所拥有的示例表:

ID      Color
=============
0       red
0       red
0       blue
1       red
1       yellow
1       yellow

Now with this query I can produce this table 现在通过此查询,我可以生成该表

SELECT id, color, count(*) as num
from table group by id,color 

ID      Color      num    
=======================
0       red         2
0       blue        1
1       red         1
1       yellow      2

And with this query I can produce this table 通过此查询,我可以生成此表

SELECT id, count(*) as num
from table group by id

ID      num    
============
0        3
1        3

But I'm looking to have an output like this. 但我希望有这样的输出。 So I'm trying to figure out a way to combine those two above queries to produce this output table. 因此,我试图找出一种方法来组合上述两个查询以生成此输出表。

ID      Color      num    
=======================
0       red         0.667 = 2/3 
0       blue        0.333 = 1/3
1       red         0.333 = 1/3
1       yellow      0.667 = 2/3

You can use the count window function in dividing those values. 您可以使用count窗口功能对这些值进行除法。

SELECT distinct id, color, 
1.0*count(*) over(partition by color,id)/count(*) over(partition by id) as num
from table 

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

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