sql - 是否有一个二维函数可以通过两列的要求满足这个组,或者有更多的 sql 方法吗?
问题描述
我有一个表,需要通过两列或产生预期分组标准的那些函数进行分组。这令人惊讶地变成了一个有趣的数学挑战,但我也很高兴看到如何在标准 SQL 解决方案中解决它。
我有下表:
create table temp (a integer, x integer, y integer);
insert into temp values (3, 0, 1);
insert into temp values (3, 1, -1);
insert into temp values (4, 0, 1);
insert into temp values (4, 1, -1);
insert into temp values (4, 0, -1);
insert into temp values (4, 1, 1);
我想将行组合在一起:
- 1 和 2
- 3和4
- 5 和 6
因此,选择将是:
select a
from temp
group by a, f(x, y)
为此,我需要一个f(x, y)
基于可用的 SQLite 整数运算符(即 *、+、-、/)构建的函数,因此我需要一个这样的函数:
f(0, 1) = f(1, -1) 和
f(0, -1) = f(1, 1)
我尝试了多种可能性,但无法弄清楚这样的分组功能......有什么聪明的想法吗?:)
是否有针对此问题的替代 SQL 解决方案?
解决方案
好吧,您可以使用case
表达式定义这样的“函数”:
(case when x = 0 and y = 1 then 1
when x = 1 and y = -1 then 1
when x = 0 and y = -1 then 2
when x = 1 and y = 1 then 2
end)
如果你想要一个算术表达式:
(2 * x * y - y)
推荐阅读
- matplotlib - 设置绘图背景时的白色背景
- r - 如何在R中找到数据框的几列之间的交集?
- python - 在 Python 中按顺序将 JSON 对象写回 .json 文件
- c++ - 您可以在不使用数组的情况下将不同数量的相同类型的参数传递给函数吗?
- php - Angularjs分页根据限制显示内容,但不会显示页码以在页面之间导航
- haskell - 已经实现的“没有实例”特征
- couchbase - Phalcon 可以支持其他 NoSQL 吗?
- reactjs - React Native Navigation with React Native Admob 关于
- c# - Unity navmesh ai 卡住了
- file-upload - 用于 firebase_storage 的 Flutter OnProgressListener?