select 行如何具有不同的列值并共享相同的列 [日期值]
How select rows that have differents column values and share the same column [date value]
我正在尝试进行一些行组合。我的table是这样的
┌─────────┬────────────────┬────────────────┐
│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 │
└─────────┴────────────────┴────────────────┘
如何仅 select 日期相同的操作,这样结果集将是:
┌─────────┬────────────────┬────────────────┐
│Machine_N│ Date │ Action │
├─────────┼────────────────┼────────────────┤
│ RS1│ 2018-02-08 │ Reading │
│ RS1│ 2018-02-08 │ Referred │
│ RS2│ 2018-01-31 │ Reading │
│ RS2│ 2018-01-31 │ 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);
另一种方法使用 window 函数:
select t.*
from (select t.*, count(*) over (partition by machine_n, date) as cnt
from t
) t
where cnt > 1;
使用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
);
我正在尝试进行一些行组合。我的table是这样的
┌─────────┬────────────────┬────────────────┐ │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 │ └─────────┴────────────────┴────────────────┘
如何仅 select 日期相同的操作,这样结果集将是:
┌─────────┬────────────────┬────────────────┐ │Machine_N│ Date │ Action │ ├─────────┼────────────────┼────────────────┤ │ RS1│ 2018-02-08 │ Reading │ │ RS1│ 2018-02-08 │ Referred │ │ RS2│ 2018-01-31 │ Reading │ │ RS2│ 2018-01-31 │ 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);
另一种方法使用 window 函数:
select t.*
from (select t.*, count(*) over (partition by machine_n, date) as cnt
from t
) t
where cnt > 1;
使用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
);