计算在日期之间更改的记录

时间:2015-03-09 19:47:11

标签: mysql sql database

我有三个表ticketsthreads以及threadstatuses,其中包含简化架构 -

CREATE TABLE `tickets` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `subject` varchar(255) NOT NULL,
  `ticketStatuses_id` int(10) unsigned NOT NULL,
  `createdAt` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `updatedAt` datetime NOT NULL DEFAULT '0000-00-00 00:00:00'
  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=83670708 DEFAULT CHARSET=utf8;

CREATE TABLE `threads` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `tickets_id` int(10) unsigned NOT NULL,
  `body` longtext NOT NULL,
  `assign_ticketStatuses_id` int(10) unsigned DEFAULT NULL,
  `createdAt` datetime NOT NULL,
  `updatedAt` datetime NOT NULL,
  PRIMARY KEY (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=31046 DEFAULT CHARSET=utf8;

CREATE TABLE `ticketstatuses` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  `createdAt` datetime NOT NULL,
  `updatedAt` datetime NOT NULL,
  PRIMARY KEY (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

您可以看到threadstickets都引用了ticketstatus。这允许我显示票证何时改变状态。我需要查询的是获取在给定日期范围内每天具有每种状态的票数的总和。因此,用户可以询问“告诉我过去7天内每天开出或关闭的门票数量(或其他任何其他内容)”。这里的最终目标是建立一个时间序列图表。

无论如何,我已经将一个公认的复杂且不太高效的查询混合在一起,这个查询给了我一天的结果,但我无法弄清楚如何修复它来计算每一天的计数。我不需要知道当天有多少票变成了状态(这很容易),但是在某一天有这种状态。这就是我提出的 -

    SELECT SUM(total) as total, name
    FROM (
        SELECT COUNT(th.id) as total, ts.name
        FROM ticketstatuses ts
        INNER JOIN threads th ON ts.id = th.assign_ticketStatuses_id
        LEFT OUTER JOIN threads nextThread ON th.tickets_id = nextThread.tickets_id
            AND nextThread.createdAt > th.createdAt
            AND nextThread.assign_ticketStatuses_id IS NOT NULL
        WHERE /* Need something different here for the range */ DATE('2015-03-04') BETWEEN DATE(th.createdAt) AND DATE(nextThread.createdAt)
        GROUP BY th.assign_ticketStatuses_id

        UNION

        /* Gives me tickets that are new (have not had a status change) */
        SELECT SUM(c) as total, name
        FROM (
            SELECT COUNT(t.id) c, ts.name as name
            FROM ticketstatuses ts
            INNER JOIN tickets t ON ts.id = t.ticketStatuses_id
            INNER JOIN threads th ON th.tickets_id = t.id
            WHERE th.assign_ticketStatuses_id IS NULL
            GROUP BY th.tickets_id
            HAVING COUNT(th.id) = 1
        ) recs
        GROUP BY recs.name
    ) recs
    GROUP BY recs.name

1 个答案:

答案 0 :(得分:1)

(编辑:更新的查询)我在MySQL上非常生疏,我不再在我的机器上安装它,但我认为你可以这样做:

SELECT dte, name, COUNT(name) FROM
  (SELECT ts.name, Date_Format(COALESCE(th.updatedAt, th.createdAt), '%Y-%m-%d') as dte 
  FROM threads th
  INNER JOIN tickets t ON t.id = th.tickets_id
  INNER JOIN ticketstatuses ts ON th.assign_ticketStatuses_id = ts.id) AS j
GROUP BY dte, name

我有理由相信这会给你一个按日期分组的计数列表,然后是ticketStatus.name,但是对于那些在MySQL中有更多专业知识的人来说,我更愿意接受修正。与此同时,上述查询的here is a SQLFiddle