【问题标题】:How to count a number of unique rows considering that A, B row = B, A row考虑到 A,B 行 = B,A 行,如何计算多个唯一行
【发布时间】:2019-08-23 22:21:41
【问题描述】:

我是 SQL 新手,因此对于可能出现的错误和不正确的问题,我提前表示歉意。

我正在尝试解决以下任务:

有一个包含两列的表。

我的任务是计算唯一行的数量,考虑到具有相同信息(无论顺序如何)的行被计为 1。

EG。行[1] a b 和行[2] b a 应计为1

所以查询的结果应该是3

【问题讨论】:

  • 你的 DBMS 是什么?
  • 我正在使用 SQL Server。抱歉忘记指定了。

标签: sql sql-server


【解决方案1】:

你可以使用聚合:

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);

许多数据库都支持least()greatest() 函数,它们稍微简化了这个逻辑。

【讨论】:

    【解决方案2】:

    尝试以下方法:

    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
    

    例如here

    【讨论】:

      【解决方案3】:

      这不是最有效的方法,但如果你不需要group by,这里还有另一种方法:

      select 
      count(distinct case when col2<col1 then concat(col2,col1) else concat(col1,col2) end)
      from your_table;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-23
        • 2018-09-02
        • 1970-01-01
        • 1970-01-01
        • 2013-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多