我有一张桌子,我正在处理这些句柄"门票" (状态="打开"或状态="关闭")。当故障单关闭时,系统会创建一个重复的条目,而不是更改状态,而是关闭"关闭"状态。
使用" ticket_number"的关键字段,如何修改下面的查询以忽略任何状态="打开"如果是另一条记录,则为#34; ticket_number"字段存在"关闭"状态?
我无法使用" DISTINCT"而且我对如何根据字段值从查询中有选择地过滤(接近)重复记录感到有点迷失。
感谢您的帮助。
SELECT (@cnt := @cnt + 1) AS item_number, t.*
FROM test t
CROSS JOIN (SELECT @cnt := 0) AS dummy
WHERE created >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
AND created<= NOW()
ORDER BY created_at DESC
答案 0 :(得分:1)
您需要将列表放入查询中以进行交叉连接。将其用作FROM语句,或将其实现为临时表并在FROM中使用它。
SELECT * FROM(
select a.*, b.status as closedstatus
from test.tickets a
left join (select ticketid, status from test.tickets where status='closed') b on a.ticketid=b.ticketid
where a.status='open') t
WHERE closedstatus is null
答案 1 :(得分:1)
如果数据中有某些内容标识了故障单状态更改的顺序,例如自动增量ID字段或日期,那么您可以选择上一个状态事件,例如
drop table if exists t;
create table t(id int auto_increment primary key,ticket_number int, status varchar(6));
insert into t (ticket_number,status) values
(1,'open'),(2,'open'),(2,'closed'),(3,'open'),(3,'closed'),(3,'open'),
(4,'open'),(4,'closed'),(4,'open'),(4,'closed');
select *
from t
where id = (select max(t1.id) from t t1 where t1.ticket_number = t.ticket_number)
and t.status = 'open';
MariaDB [sandbox]> select *
-> from t
-> where id = (select max(t1.id) from t t1 where t1.ticket_number = t.ticket_number)
-> and t.status = 'open';
+----+---------------+--------+
| id | ticket_number | status |
+----+---------------+--------+
| 1 | 1 | open |
| 6 | 3 | open |
+----+---------------+--------+
2 rows in set (0.00 sec)