sql - 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 在选择查询中过滤掉了其中的一些值?
解决方案
你想要一个窗口函数:
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 . . .;
推荐阅读
- lisp - Racket 中 C 浮点数的正确指针类型转换是什么?
- php - MongoDB PHP 驱动程序无法在 Ubuntu AWS 上运行
- angular - 如何修复从 Angular 7 到 Jersey 服务的 http 调用中的会话丢失
- swift - 核心数据:保存对象时“调用”扩展中的计算属性
- android - Android studio kotlin 画线功能
- javascript - 如何删除选定的列表元素,而不是仅删除顶部 li 标记
- php - 如何解决我的代码的未定义索引错误
- android - 如何实现与另一个 EditText 重叠的 EditText?
- php - 如何将表单数据提交到 MySQL 数据库
- php - Symfony - 可捕获的致命错误:类 App\Entity\Question 的对象无法转换为字符串