具有基于值的动态列的Piviot表

时间:2019-04-24 21:17:41

标签: mysql

我正在尝试创建一个表,该表根据来源和案件状态显示案件计数。我相信可以在MySQL中完成

表一包含以下数据(imports__cases)

  • caseid
  • 起源
  • 创建日期

表2包含以下数据(imports_cases__history)

此表包含一个案例的运行更改,出于历史目的,这是我可以获取最近状态的地方

  • caseid
  • 听觉
  • 字段
  • 值(创建动态列:新的,打开的,待处理的,已解决的,已关闭的)
  • 创建日期

我要寻找的最终结果如下:

-----------------------------------------------------------------
|         |   new  |  open  |  pending  |  solved    |  closed  |
-----------------------------------------------------------------
| email   |    5   |   10   |     3     |     20     |     5    |
-----------------------------------------------------------------
| Phones  |   20   |    2   |     8     |     40     |     60   |
-----------------------------------------------------------------
| Chats   |    6   |    1   |     3     |     23     |     14   |
-----------------------------------------------------------------
| Socials |    8   |   56   |     43    |     95     |    86    |
-----------------------------------------------------------------

我尝试了以下语句,该语句为我提供了行,但没有像上面那样的聚合,分组或动态列

   SELECT 
    `a`.`origin`, `b`.`value`, `b`.`max`
FROM
    (`imports__cases` AS `a`
    INNER JOIN (SELECT 
        `a`.`caseid`, `a`.`auditid`, `b`.`max`, `a`.`value`
    FROM
        `imports__cases__history` AS `a`
    INNER JOIN (SELECT 
        `caseid`,
            MAX(`auditid`) AS `auditid`,
            MAX(`created`) AS `max`
    FROM
        `imports__cases__history` AS `a`
    WHERE
      `field` = 'status'
    GROUP BY `caseid`) AS `b` ON `a`.`auditid` = `b`.`auditid`) AS `b` ON `a`.`caseid` = `b`.`caseid`);

结果

-------------------------------------------------
|  origin   |   value   |      date created     |
-------------------------------------------------
|  'email'  |  'new'    | '2017-08-21 19:02:38' |
-------------------------------------------------
|  'phone'  | 'closed'  | '2017-08-23 20:49:35' |
-------------------------------------------------
|  'chat'   | 'pending' | '2017-08-30 19:18:34' |
-------------------------------------------------
|  'social' | 'solved'  | '2017-08-31 05:21:44' |
-------------------------------------------------
|  'email'  |  'new'    | '2017-09-26 19:02:38' |
-------------------------------------------------
|  'phone'  | 'closed'  | '2017-09-27 20:49:35' |
-------------------------------------------------
|  'chat'   | 'pending' | '2017-09-30 19:18:34' |
-------------------------------------------------
|  'social' | 'solved'  | '2017-09-31 05:21:44' |
-------------------------------------------------

0 个答案:

没有答案