Sql 考虑到a,B行=B,a行,如何计算唯一行的数量
我是SQL新手,因此对于可能出现的错误和不正确的问题,我提前表示歉意 我正在尝试解决以下任务: 有一个有两列的表 我的任务是计算唯一行的数量,考虑到不管顺序如何,具有相同信息的行都被计算为1 第[1]ab行和第[2]ba行应计为1Sql 考虑到a,B行=B,a行,如何计算唯一行的数量,sql,sql-server,Sql,Sql Server,我是SQL新手,因此对于可能出现的错误和不正确的问题,我提前表示歉意 我正在尝试解决以下任务: 有一个有两列的表 我的任务是计算唯一行的数量,考虑到不管顺序如何,具有相同信息的行都被计算为1 第[1]ab行和第[2]ba行应计为1 因此,查询结果应为3您可以使用聚合: select (case when col1 < col2 then col1 else col2 end) as least, (case when col1 < col2 then col2 else
因此,查询结果应为3您可以使用聚合:
select (case when col1 < col2 then col1 else col2 end) as least,
(case when col1 < col2 then col2 else col3 end) as greatest,
count(*)
from t
group by (case when col1 < col2 then col1 else col2 end),
(case when col1 < col2 then col2 else col3 end);
许多数据库都支持最小和最大的函数,这会稍微简化此逻辑。请尝试以下操作:
select *, count(*)
from
(
select
case when Column2<Column1 then Column2 else Column1 end as Column1,
case when Column1>Column2 then Column1 else Column2 end as Column2
from tab
) as t
group by Column1,Column2
示例。这不是最有效的方法,但如果您不需要分组,这里有另一种方法:
select
count(distinct case when col2<col1 then concat(col2,col1) else concat(col1,col2) end)
from your_table;
你的数据库管理系统是什么?我使用的是SQL Server。对不起,忘记指定了。