首页 > 解决方案 > SQL 计算每一行的不同值

问题描述

我有一张看起来像这样的桌子

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

我想在我的选择命令中添加一个基于值计算 GROUP 的列,如下所示:

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

在此示例中,值 1 获得了两组 A 和 C 的其他值。

另外是否可以考虑 VALUES 和 GROUP 的所有值,即使 WHERE 在选择查询中过滤掉了其中的一些值?

标签: sqlsqlite

解决方案


你想要一个窗口函数:

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

如果查询有where子句,您就会遇到问题。where应用于窗口函数。所以你需要一个计数的子查询:

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

或者在某些情况下关联子查询可能很方便:

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

推荐阅读