首页 > 解决方案 > 是否有一个二维函数可以通过两列的要求满足这个组,或者有更多的 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);

我想将行组合在一起:

因此,选择将是:

select a
from temp
group by a, f(x, y)

为此,我需要一个f(x, y)基于可用的 SQLite 整数运算符(即 *、+、-、/)构建的函数,因此我需要一个这样的函数:

是否有针对此问题的替代 SQL 解决方案?

标签: sqlsqlitemathgroup-by

解决方案


好吧,您可以使用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)

推荐阅读