编写 MySQL 查询以获得测试表的预期结果 [英] Write MySQL query to get expected result for test table

查看:52
本文介绍了编写 MySQL 查询以获得测试表的预期结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MySQL 数据库.

I am working with MySQL database.

表格包含以下数据:

<头>
iduaid属性价值时间风险因素
11234文件路径存在16123
21234文件路径不存在16124关键
31234文件路径存在16125

所需的结果应如下所示:

the required result should be like below:

<头>
属性风险因素UAID失败值现值
文件路径关键1234不存在存在

说明:

  1. 我们需要显示具有关键风险因素的数据.

  1. we need to show data which have risk factor critical.

失败值 = 在风险因素至关重要时(最新的),然后该属性的值表示为失败值

Failed Value = at the time (latest one) when risk factor is critical then value for that attribute represent as failed value

当前值 = 它表示为数据库中该属性的当前值.

Present value = it is represented as current value for that attribute in database.

我尝试了两个 sql 查询的解决方案.一种用于获取风险因子等于关键的行.第二个用于获取每个唯一属性的当前值.然后对来自两个查询的数据进行一些格式化.

i have tried with the solution of two sql queries. one for taking getting rows which have risk factor equal to critical. and the second one for getting current value of each unique attribuite. and then some formatting of data from the both queries.

我正在寻找可以根据要求消除数据格式化的额外开销的解决方案.

I am looking for solution which removes the extra overhead of data formatting according to requirement.

架构表(id,uaid,attribute,value,time,risk_factor)

Schema table(id,uaid,attribute,value,time,risk_factor)

推荐答案

假设一个组是一个具有相同 (uaid, attribute) 值的行集:

Assuming that a group is a rowset with the same (uaid, attribute) values:

WITH cte AS (
SELECT DISTINCT
       attribute,
       'CRITICAL' `Risk Factor`,
       uaid,
       FIRST_VALUE(value) OVER (PARTITION BY uaid, attribute 
                                ORDER BY `risk factor` = 'CRITICAL' DESC, `time` DESC) `Failed Value`,
       FIRST_VALUE(value) OVER (PARTITION BY uaid, attribute 
                                ORDER BY `time` DESC) `Present Value`,
       SUM(`risk factor` = 'CRITICAL') OVER (PARTITION BY uaid, attribute) is_critical
FROM source_table
)
SELECT Attribute, `Risk Factor`, UAID, `Failed Value`, `Present Value`
FROM cte
WHERE is_critical; 

小提琴

这篇关于编写 MySQL 查询以获得测试表的预期结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆