Sql 如何选择列值不同且共享同一列的行[日期值]
我正在尝试做一些行的组合。我的桌子是这样的 ┌─────────┬────────────────┬────────────────┐ │Machine_N│ Date │ Action │ ├─────────┼────────────────┼────────────────┤ │ RS1│ 2018-02-08 │ Reading │ │ RS1│ 2018-02-08 │ Referred │ │ RS1│ 2018-02-16 │ Reading │ │ RS2│ 2018-01-31 │ Reading │ │ RS2│ 2018-01-31 │ Referred │ └─────────┴────────────────┴────────────────┘ ┌─────────┬────────────────┬────────────────┐ │机器│ 日期│ 行动│ ├─────────┼────────────────┼────────────────┤ │ RS1│ 2018-02-08 │ 阅读│ │ RS1│ 2018-02-08 │ 援引的│ │ RS1│ 2018-02-16 │ 阅读│ │ RS2│ 2018-01-31 │ 阅读│ │ RS2│ 2018-01-31 │ 援引的│ └─────────┴────────────────┴────────────────┘ 如何仅选择日期相同的操作,以便结果集为: ┌─────────┬────────────────┬────────────────┐ │Machine_N│ Date │ Action │ ├─────────┼────────────────┼────────────────┤ │ RS1│ 2018-02-08 │ Reading │ │ RS1│ 2018-02-08 │ Referred │ │ RS2│ 2018-01-31 │ Reading │ │ RS2│ 2018-01-31 │ Referred │ └─────────┴────────────────┴────────────────┘ ┌─────────┬────────────────┬────────────────┐ │机器│ 日期│ 行动│ ├─────────┼────────────────┼────────────────┤ │ RS1│ 2018-02-08 │ 阅读│ │ RS1│ 2018-02-08 │ 援引的│ │ RS2│ 2018-01-31 │ 阅读│ │ RS2│ 2018-01-31 │ 援引的│ └─────────┴────────────────┴────────────────┘Sql 如何选择列值不同且共享同一列的行[日期值],sql,sql-server,count,sql-order-by,having-clause,Sql,Sql Server,Count,Sql Order By,Having Clause,我正在尝试做一些行的组合。我的桌子是这样的 ┌─────────┬────────────────┬────────────────┐ │Machine_N│ Date │ Action │ ├─────────┼────────────────┼────────────────┤ │ RS1│ 2018-02-08 │ Reading │ │ RS1│ 2018-02-08 │ Referred
我试过使用having count子句,但没有成功。任何帮助都将不胜感激。如果您没有重复项,您可以使用
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 *
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
);
您使用的是哪种数据库管理系统?(SQL Server、MySQL、Oracle等)我正在使用SQL Server。
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
);