我不完全确定如何组合单个 SQLite 查询来实现以下目标。我可以让零碎的东西发挥作用,但似乎无法将它们全部融合成一个。
我有一个看起来像这样的表(真实数据集有几个GB):
| ID | ColumnA | ColumnB | ColumnC | ColumnD |
| 1 | 21 | 34 | 10 | 0.12654 |
| 2 | 21 | 34 | 20 | 0.25478 |
| 3 | 21 | 46 | 10 | 0.43564 |
| 4 | 21 | 46 | 20 | 1.02487 |
| 5 | 34 | 21 | 10 | 0.01476 |
| 6 | 34 | 21 | 20 | 0.87265 |
| 7 | 34 | 46 | 10 | 0.46478 |
| 8 | 34 | 46 | 20 | 0.13665 |
| 9 | 46 | 21 | 10 | 0.04189 |
| 10 | 46 | 21 | 20 | 0.91754 |
| 11 | 46 | 34 | 10 | 0.73688 |
| 12 | 46 | 34 | 20 | 0.24299 |
此数据是由嵌套 do-loop 生成的,用于我正在执行的一些模拟。
从这个表中,我基本上需要提取一个如下所示的表,以便我可以绘制颜色/热图。
| ID | ColumnA | ColumnB | ColumnC | ColumnD |
| 1 | 21 | 34 | 10 | 0.12654 |
| 3 | 21 | 46 | 10 | 0.43564 |
| 5 | 34 | 21 | 10 | 0.01476 |
| 8 | 34 | 46 | 20 | 0.13665 |
| 9 | 46 | 21 | 10 | 0.04189 |
| 12 | 46 | 34 | 20 | 0.24299 |
因此,这将使我能够使用 2D 数组基于 ColumnD 值制作颜色图(对角线应设置为零,因为给定行的 ColumnA 和 ColumnB 的值永远不相等;因此对角线的数据数据库中不存在):
| 21 | 34 | 46
------------------
21 | 0 | |
------------------
34 | | 0 |
------------------
46 | | | 0
我的问题基本上是如何设置单个查询来聚合进入 2D 数组的所有数据以生成颜色图。
需要注意的是,ColumnA 和 ColumnB 基本上由同一组整数填充。我可以使用 DISTINCT 获取唯一的整数值列表。我发现了一些关于在多个列中选择 DISTINCT 的 SO 线程,但是没有一个示例显示如何使用聚合器来选择其他列中的值。在本例中,我想使用 min() 为 ColumnA 和 ColumnB 中的每对 id 选择 ColumnD 中的最小值。在单个列上选择 DISTINCT 不起作用,因为它是不同的坐标对(ColumnA、ColumnB)。
任何帮助将不胜感激!
最佳答案
对我来说,您似乎想要 ColumnA
和 ColumnB
对的 ColumnD
的最小值。如果您不关心 id
或 ColumnC
,一个简单的 group by
就足够了:
select ColumnA, ColumnB, min(ColumnD)
from table t
group by ColumnA, ColumnB;
如果您确实需要该行中的所有值,您可以加入
回来获取它们:
select t.*
from table t join
(select ColumnA, ColumnB, min(ColumnD) as ColumnD
from table t
group by ColumnA, ColumnB
) tt
on t.ColumnA = tt.ColumnA and t.ColumnB = tt.ColumnB and
t.ColumnD = tt.ColumnD;
这假设 ColumnD
对于 ColumnA
和 ColumnB
中的值永远不会重复。
关于python - SQLite 跨具有重复分组行的多列进行 SELECT 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28279996/