![](/img/trans.png)
[英]MYSQL How to group entries by ID and create a column with grouped entries?
[英]How to get entries which are grouped and satisfy restriction within the group?
在表 REPORT 中有以下 3 列:
下面的例子:
RID | Type | TIMESTAMP |
-----+---------+-------------------+
4 | New | 2019-10-27 10:35 |
4 | Cancel | 2019-10-27 09:35 |
3 | Cancel | 2019-10-27 07:35 |
2 | New | 2019-10-27 07:35 |
1 | Cancel | 2019-10-27 09:35 |
1 | Cancel | 2019-10-27 08:35 |
1 | New | 2019-10-27 07:35 |
我想獲取在某個時候創建然后取消的所有報告,以便取消最新的 state。 可能會取消不存在的報告,或者先取消然后新條目的條目,所有這些都應排除在外。
到目前為止,我的嘗試是使用嵌套查詢來獲取所有取消,這些取消具有相應的新條目,但不知道如何考慮它們的時間戳,以排除具有序列 cancel->new 的條目
SELECT
RID
FROM
REPORT
WHERE
TYPE = 'Cancel'
AND RID IN (
SELECT
RID
FROM
REPORT
WHERE
TYPE = 'New'
);
我對示例的期望是獲得 RID 1,我只對 RID 感興趣。
使用:MySQL 5.7.27 InnoDB
隨着EXISTS
:
select distinct r.rid
from report r
where r.type = 'Cancel'
and exists (
select 1 from report
where rid = r.rid and type='New' and timestamp < r.timestamp
)
請參閱演示。
或者:
select rid
from report
group by rid
having
min(case when type = 'New' then timestamp end) <
min(case when type = 'Cancel' then timestamp end)
請參閱演示。
結果:
| rid |
| --- |
| 1 |
我會使用相關子查詢獲得最新類型。 然后檢查“取消”:
select t.*
from t
where t.timestamp = (select max(t2.timestamp)
from t t2
where t2.rid = t.rid
) and
t.type = 'Cancel';
如果您只想rid
和約會,那么另一種有趣的方式是使用聚合:
select rid, max(timestamp)
from t
group by rid
having max(timestamp) = max(case when type = 'Cancel' then timestamp end);
這里的邏輯是獲取最大日期也是最大取消日期的時間戳。
在我的腦海中,可能有幾個錯別字,可能不是最好的,但應該很容易理解......
SELECT n.RID FROM (
SELECT RID, TYPE, MIN(DATETIME) AS FirstAdd
FROM REPORT
WHERE TYPE = 'New'
GROUP BY RID, TYPE) n INNER JOIN (
SELECT RID, TYPE, MAX(DATETIME) AS LastCancel
FROM REPORT
WHERE TYPE = 'Cancel'
GROUP BY RID, TYPE) c ON n.RID = c.RID
AND n.FirstAdd < c.LastCancel
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.