非常复杂的SQL查询

时间:2019-04-22 11:42:38

标签: mysql sql

我正在使用MySql,应该创建一个非常复杂的报告来显示事件状态。

例如:

event_id   |  state        |  create_time
----------------------------------------------------
1          |    PENDING    | 2019-04-21 12:55:59.312
1          |   COMPLETED   | 2019-04-21 12:55:59.339
2          |   PENDING     | 2019-04-21 11:40:21.699
3          |   PENDING     | 2019-04-21 11:40:21.699
3          |   FAILED      | 2019-04-21 11:40:21.600
3          |   COMPLETED   | 2019-04-21 11:40:21.578

我需要根据州的偏好选择行:

  • 失败+完成+待处理->失败
  • 已完成+待处理->已完成
  • 仅待处理->待处理

应使用OFFSET和SIZE分页。

每个事件将显示一次。

预期结果:

event_id   |  state        |  create_time
----------------------------------------------------
1          |   COMPLETED   | 2019-04-21 12:55:59.339
2          |   PENDING     | 2019-04-21 11:40:21.699
3          |   FAILED      | 2019-04-21 11:40:21.600

如何在单个SQL查询中执行此操作。

关于, 伊多

3 个答案:

答案 0 :(得分:3)

我怀疑您希望使用某些条件逻辑进行聚合,例如:

select event_id,
       (case when sum(state = 'FAILED') > 0 then 'FAILED'
             when sum(state = 'COMPLETED') > 0 then 'COMPLETED'
             when sum(state = 'PENDING') > 0 then 'PENDING'
        end) as new_state
from t
group by event_id;

答案 1 :(得分:2)

您可以使用coalesce()进行聚合:

select event_id,
       coalesce(max(case when state = 'FAILED' then 'FAILED' end),
                max(case when state = 'COMPLETED' then 'COMPLETED' end),
                'PENDING'     
               )
from table t
group by event_id;

答案 2 :(得分:1)

另一个选择是将这些状态首选项作为位掩码进行处理。

注意 此方法假定event_id没有重复的统计信息。

查询

SELECT 
 t.*
FROM (

SELECT 
   t.event_id
 , SUM(bitmask_table.bitmask) AS total_bitmask
FROM (
  SELECT
    DISTINCT 
       state
     , CASE 
        WHEN state = 'PENDING'
        THEN 2

        WHEN state = 'COMPLETED'
        THEN 4

        WHEN state = 'FAILED'
        THEN 8
       END AS bitmask
  FROM
   t 
) AS bitmask_table
INNER JOIN 
 t
ON
 t.state = bitmask_table.state
GROUP BY 
 t.event_id

) AS group_bitmasked
INNER JOIN 
 t
ON
  group_bitmasked.event_id = t.event_id
AND
 t.state = CASE
    WHEN group_bitmasked.total_bitmask & 8 AND group_bitmasked.total_bitmask & 4 AND  group_bitmasked.total_bitmask & 2
    THEN 'FAILED'

    WHEN group_bitmasked.total_bitmask & 4 AND group_bitmasked.total_bitmask & 2
    THEN 'COMPLETED'  

    WHEN group_bitmasked.total_bitmask & 2
    THEN 'PENDING'      
   END

结果

| event_id | state     | create_time             |
| -------- | --------- | ----------------------- |
| 1        | COMPLETED | 2019-04-21 12:55:59.339 |
| 2        | PENDING   | 2019-04-21 11:40:21.699 |
| 3        | FAILED    | 2019-04-21 11:40:21.600 |

请参阅demo