【问题标题】:How select rows that have differents column values and share the same column [date value]如何选择具有不同列值并共享同一列的行[日期值]
【发布时间】:2018-05-10 15:52:32
【问题描述】:

我正在尝试做一些行组合。我的桌子是这样的

┌──────────┬────────────────┬────────────────┐ │Machine_N│日期│动作│ ├──────────┼────────────────┼────────────────┤ │ RS1│ 2018-02-08 │ 阅读 │ │ RS1│ 2018-02-08 │ 参考 │ │ RS1│ 2018-02-16 │ 阅读 │ │ RS2│ 2018-01-31 │ 阅读 │ │ RS2│ 2018-01-31 │ 参考 │ └──────────┴────────────────┴────────────────┘

如何仅选择日期相同的操作,以便结果集为:

┌──────────┬────────────────┬────────────────┐ │Machine_N│日期│动作│ ├──────────┼────────────────┼────────────────┤ │ RS1│ 2018-02-08 │ 阅读 │ │ RS1│ 2018-02-08 │ 参考 │ │ RS2│ 2018-01-31 │ 阅读 │ │ RS2│ 2018-01-31 │ 参考 │ └──────────┴────────────────┴────────────────┘

我尝试了一个有计数子句但没有运气。任何帮助将不胜感激。

【问题讨论】:

  • 您使用的是哪个 DBMS? (SQL Server、MySQL、Oracle 等)
  • 我正在使用 SQL Server。

标签: sql sql-server count sql-order-by having-clause


【解决方案1】:

假设你没有重复,你可以使用exists:

select t.*
from t
where exists (select 1 from t t2 where t2.machine_n = t.machine_n and t2.date = t.date and t2.action <> t.action);

另一种使用窗口函数的方法:

select t.*
from (select t.*, count(*) over (partition by machine_n, date) as cnt
      from t
     ) t
where cnt > 1;

【讨论】:

    【解决方案2】:

    使用subquery

    select * 
    from table t
    where date = (select top (1) [date] 
                  from table 
                  where machine_n = t.machine_n 
                  group by date
                  order by COUNT(1) desc
                 );
    

    但是大多数 DBMS 没有 TOP 子句,所以你可以使用 LIMIT 子句来代替

    select * 
    from table t
    where date = (select [date] 
                  from table 
                  where machine_n = t.machine_n 
                  group by date
                  order by COUNT(1) desc
                  LIMIT 1
                  );
    

    【讨论】:

      猜你喜欢
      • 2013-01-17
      • 1970-01-01
      • 2017-02-14
      • 2012-05-25
      • 2014-12-08
      • 2019-05-31
      • 2015-07-17
      • 1970-01-01
      • 2017-12-24
      相关资源
      最近更新 更多