在SQL中运行票证计数器

时间:2015-11-11 18:44:45

标签: mysql sql

我正在尝试将一个运行计数器作为第一列,以便轻松查看为代理分配的票数。数字模拟器可以工作,但不是提高代理的票号,而是计算票证日期。我目前的代码是:

Set @row_num = 0;
SELECT @row_num := @row_num + 1 as row_number
     , s.firstname
     , s.lastname
     , t.number
     , ts.name AS status
     , o.name, t.created
  FROM ost_ticket t
   JOIN ost_ticket_status ts ON t.status_id = ts.id 
   JOIN ost_staff s ON t.staff_id = s.staff_id
   JOIN ost_user u ON t.user_id = u.id
   JOIN ost_organization o ON u.org_id = o.id
   JOIN (SELECT @row_num:= 0) N
 WHERE s.staff_id IN (27,35,43,45)
   AND t.created >= CURDATE() - INTERVAL 7 DAY
 ORDER BY s.lastname

如果代理商拥有1,2,3,然后为新代理商重置,我最好如何更改?

1 个答案:

答案 0 :(得分:0)

你需要一个不同的变量来跟踪代理人的变化。

SET @row_num := 0;
SET @agent   :='';

SELECT 
       @row_number := IIF(@agent = s.firstname + s.lastname, 
                         @row_number + 1,  1 
                        ) AS row_number,
       @agent := s.firstname + s.lastname AS agent,
       s.firstname, 
       s.lastname, 
       t.number, 
       ts.name AS status, 
       o.name, 
       t.created
FROM ost_ticket t
   JOIN ost_ticket_status ts ON t.status_id = ts.id 
   JOIN ost_staff s ON t.staff_id = s.staff_id
   JOIN ost_user u ON t.user_id = u.id
   JOIN ost_organization o ON u.org_id = o.id
WHERE s.staff_id IN (27,35,43,45)
AND t.created >= CURDATE() - INTERVAL 7 DAY
ORDER BY s.lastname