简体   繁体   English

SQL 计算每行的不同值

[英]SQL count distinct values for each row

I got a table looking like this我有一张看起来像这样的桌子

+-----+---------+
|Group|Value    |
+-----+---------+
|A    |1        |
+-----+---------+
|B    |2        |
+-----+---------+
|C    |1        |
+-----+---------+
|D    |3        |
+-----+---------+

And I would like to add a column in my select command that count GROUP based on value, lookin like this:我想在我的 select 命令中添加一个列,该列根据值对 GROUP 进行计数,如下所示:

+-----+---------+---------+
|Group|Value    | COUNT   |
+-----+---------+---------+
|A    |1        |2        |
+-----+---------+---------+
|B    |2        |1        |
+-----+---------+---------+
|C    |1        |2        |
+-----+---------+---------+
|D    |3        |1        |
+-----+---------+---------+

Value 1 got the two groups A and C the other values for each one in this example.在此示例中,值 1 获得两组 A 和 C 其他值。

Additional is it possible to consider all values for VALUES and GROUP even if a WHERE filtered out some of them in the select query?另外,是否可以考虑 VALUES 和 GROUP 的所有值,即使 WHERE 在 select 查询中过滤掉了其中的一些值?

You want a window function:你想要一个 window function:

select t.*, count(*) over (partition by value) as count
from t;

You have a problem if the query has a where clause.如果查询有where子句,就会出现问题。 The where applies to the window function. So you need a subquery for the count: where适用于 window function。所以你需要一个子查询来计算:

select t.*
from (select t.*, count(*) over (partition by value) as count
      from t
     ) t
where . . .;

Or a correlated subquery might be convenient under some circumstances:或者在某些情况下相关子查询可能很方便:

select t.*,
       (select count(*) from t t2 where t2.value = t.value) as count
from t
where . .  .;

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

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