如何将相同的行加到不同的值之前

时间:2016-12-14 06:49:20

标签: mysql sql group-by

我有一张像这张照片的桌子。我想找到运营商的最小分配日期和最小升级日期组,直到不同的运营商来。示例前两个运算符是相同的,所以我想将这两个相加,因为不同的运算符在它们之后。

TROUBLETICKETINDEX         OPERATOR         Assign                   Escalate
    1262084                qbcca0110    12-12-2016 21:11:49  12-12-2016 21:11:49
    1262084                qbcca0110    12-12-2016 21:16:23  12-12-2016 21:16:23
    1262084                tss          12-14-2016 1:45:58   12-14-2016 1:45:58
    1262084                qbcca0110    12-14-2016 10:34:31  12-14-2016 10:34:31

请告诉我可能在mysql中吗?

我试试这个

  select th.TROUBLETICKETINDEX,
         th.OPERATOR, 
         min(th.HISTORYDATE) Assign, 
         max(th.HISTORYDATE) Escalate
    from troubleticketshistory th inner join 
         users_usergroups uug on uug.userId = th.TICKETOWNER inner join 
         usergroup ug on ug.userGroupId = uug.userGroupId
   where th.TROUBLETICKETINDEX=1262084
group by th.OPERATOR;

但是这给了我

enter image description here

但我正在寻找

enter image description here

这是我的烦恼历史表

HISTORYDATE         OPERATOR    TROUBLETICKETINDEX  TICKETOWNER USERGROUPINDEX
12-12-2016 21:11:49 qbcca0110   1262084                  24229  12016
12-12-2016 21:16:23 qbcca0110   1262084                  25111  22956
12-14-2016 1:45:58  tss         1262084                  24229  12016
12-14-2016 10:34:31 qbcca0110   1262084                  24229  12016

1 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

SELECT TROUBLETICKETINDEX,
       OPERATOR,
       MIN(HISTORYDATE) AS Assign,
       MAX(HISTORYDATE) AS Escalate
FROM (
   SELECT th.TROUBLETICKETINDEX,
          th.OPERATOR, 
          th.HISTORYDATE
          @rn := @rn + 1 AS rn,
          @grp := IF(@op = OPERATOR, @grp + 1,
                     IF(@op := OPERATOR, 1, 1)) AS grp
   FROM troubleticketshistory th
   CROSS JOIN (SELECT @rn := 0, @grp := 0, @op := '') AS vars
   WHERE th.TROUBLETICKETINDEX = 1262084
   ORDER BY th.Assign) AS t
GROUP BY TROUBLETICKETINDEX, OPERATOR, rn - grp 
ORDER BY Assign 

Demo here