Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL由两列组成,其中顺序不为';没关系_Sql_Sqlite_Group By - Fatal编程技术网

SQL由两列组成,其中顺序不为';没关系

SQL由两列组成,其中顺序不为';没关系,sql,sqlite,group-by,Sql,Sqlite,Group By,假设我有这张桌子: col1|col2|score x |y |1 y |x |2 z |w |4 w |z |2 我想用col1和col2来分组,不管值是来自col1还是col2,所以x | y和y | x被分组在一起。聚合函数可以是AVG,因此我想得到结果: col1|col2|score x |y |1.5 z |w |3 或 我知道我可以按两列进行分组,但这对我没有帮助,所以我该怎么做呢? (我使用的是SQLite3,但我想对于任何SQ

假设我有这张桌子:

col1|col2|score
x   |y   |1
y   |x   |2
z   |w   |4
w   |z   |2
我想用col1和col2来分组,不管值是来自col1还是col2,所以x | y和y | x被分组在一起。聚合函数可以是AVG,因此我想得到结果:

col1|col2|score
x   |y   |1.5
z   |w   |3

我知道我可以按两列进行分组,但这对我没有帮助,所以我该怎么做呢?
(我使用的是SQLite3,但我想对于任何SQL DB,答案都差不多)

您可以使用聚合。许多数据库支持
最小()
最大()
,这将此逻辑简化为:

select least(col1, col2) as col1, greatest(col1, col2) as col2, avg(score) as score
from t
group by least(col1, col2), greatest(col1, col2)
order by least(col1, col2), greatest(col1, col2);
在不支持这些函数的数据库中,可以使用
case
表达式:

  • least(co1,col2)
    -->
    (col1
  • 最大值(co1,col2)
    -->
    (col1

在SQLite中,您可以使用带有多个参数的
min()
max()
作为
least()
grest()
的等价物,您可以使用聚合。许多数据库支持
最小()
最大()
,这将此逻辑简化为:

select least(col1, col2) as col1, greatest(col1, col2) as col2, avg(score) as score
from t
group by least(col1, col2), greatest(col1, col2)
order by least(col1, col2), greatest(col1, col2);
在不支持这些函数的数据库中,可以使用
case
表达式:

  • least(co1,col2)
    -->
    (col1
  • 最大值(co1,col2)
    -->
    (col1
在SQLite中,您可以使用带有多个参数的
min()
max()
作为
least()
grest()
的等价物,谢谢!在SQLite3中使用了min()和max(),效果很好。谢谢!在SQLite3中使用了min()和max(),效果很好。