gpt4 book ai didi

mysql - 检索为 Mysql 中的树数据定义的最后一个值

转载 作者:可可西里 更新时间:2023-11-01 07:43:59 25 4
gpt4 key购买 nike

Product Tier1 Tier2 Tier3   value
A ANZ - - 2
A ANZ DE - 3
A ANZ DE Outlet 9
B EMEA - - 4
B EMEA IT - 6

我每次都对为产品定义的最后一个值感兴趣。例如,对于产品 A,我应该得到值 9,对于产品 B,我应该得到值 6。

我是否可以直接使用 sql 查询获取结果,或者我加载整个产品行并在后端代码中执行操作以获得最终值。什么更可取。我正在使用 MYsql。

  ANZ       2        
|
DE 3
|
OUTLET - 9 last defined level value is 9


EMEA 4
|
IT 6
|
? No value defined so last defined level value is 6

情况可以

案例一

 Product Tier1 Tier2 Tier3   value
A ANZ - - 2
A ANZ DE - 3
A ANZ DE Outlet 9

Desired result = 9

案例2

     Product Tier1 Tier2 Tier3   value
A ANZ DE Outlet 9

Desired result = 9

案例3

    Product Tier1 Tier2 Tier3   value
A ANZ - - 2
A ANZ DE Outlet 9

Desired result = 9

案例4

 Product Tier1 Tier2 Tier3   value
A ANZ - - 2
A ANZ DE - 3

Desired result = 3

案例5

 case4
Product Tier1 Tier2 Tier3 value
A ANZ - - 2

Desired result = 2

最佳答案

这是一个经过验证的解决方案,已提供数据。

SQL:

SELECT
product,
tier1,
tier2,
tier3,
value
FROM
tbl tbl2
WHERE
( tbl2.product, ((tier1 IS NOT NULL) + (tier2 IS NOT NULL ) + (tier3 IS NOT NULL)) ) IN
(
SELECT
product,
MAX( (tier1 IS NOT NULL) + (tier2 IS NOT NULL ) + (tier3 IS NOT NULL) ) maxTierCnt
FROM
tbl
WHERE
tbl.product = tbl2.product
);

输出:

mysql> SELECT * FROM tbl;
+---------+-------+-------+--------+-------+
| product | tier1 | tier2 | tier3 | value |
+---------+-------+-------+--------+-------+
| A | ANZ | NULL | NULL | 2 |
| A | ANZ | DE | NULL | 3 |
| A | ANZ | DE | Outlet | 9 |
| B | EMEA | NULL | NULL | 4 |
| B | EMEA | IT | NULL | 6 |
+---------+-------+-------+--------+-------+
5 rows in set (0.00 sec)

mysql>
mysql> SELECT
-> product,
-> tier1,
-> tier2,
-> tier3,
-> value
-> FROM
-> tbl tbl2
-> WHERE
-> ( tbl2.product, ((tier1 IS NOT NULL) + (tier2 IS NOT NULL ) + (tier3 IS NOT NULL)) ) IN
-> (
-> SELECT
-> product,
-> MAX( (tier1 IS NOT NULL) + (tier2 IS NOT NULL ) + (tier3 IS NOT NULL) ) maxTierCnt
-> FROM
-> tbl
-> WHERE
-> tbl.product = tbl2.product
-> );
+---------+-------+-------+--------+-------+
| product | tier1 | tier2 | tier3 | value |
+---------+-------+-------+--------+-------+
| A | ANZ | DE | Outlet | 9 |
| B | EMEA | IT | NULL | 6 |
+---------+-------+-------+--------+-------+
2 rows in set (0.00 sec)

关于mysql - 检索为 Mysql 中的树数据定义的最后一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35573314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com