mysql条件文本聚合

gr8qqesn  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(303)

我目前有以下输入模型:

+---------+-----------+---------+---------+--------+
| user_id |   date    | program |  type   |  more  |
+---------+-----------+---------+---------+--------+
|       1 | 23-Mar-15 | AAA     | init    |        |
|       1 | 21-May-15 | AAA     | 1/3     |        |
|       1 | 22-Sep-15 | AAA     | 1/3     |        |
|       1 | 20-Mar-16 | AAA     | 1/3     |        |
|       1 | 12-Aug-16 | CCC     | init    |        |
|       1 | 27-Jun-18 | CCC     | init    | refund |
|       2 | 16-May-16 | BBB     | init    |        |
|       2 | 12-Aug-16 | BBB     | full    |        |
|       2 | 15-Mar-17 | AAA     | 1/3     |        |
|       2 | 21-Jun-17 | AAA     | 1/3     | refund |
|       3 | 24-May-18 | BBB     | init    |        |
|       3 | 27-May-18 | BBB     | 1/3     |        |
|       3 | 27-Jun-18 | BBB     | 2/3     |        |
|       4 | 27-Jun-18 | AAA     | init    |        |
|       5 | 27-Jun-18 | AAA     | 1/3     |        |
|       5 | 27-Jun-18 | AAA     | 1/3     |        |
+---------+-----------+---------+---------+--------+

我想要的结果是:

+---------+----------+------------+
| user_id | programs | aggregated |
+---------+----------+------------+
|       1 | AAA      | full       |
|       1 | CCC      | refund     |
|       2 | BBB      | full       |
|       2 | AAA      | refund     |
|       3 | BBB      | 2/3        |
|       4 | AAA      | init       |
|       5 | AAA      | 2/3        |
+---------+----------+------------+

我正在寻找有关如何设计输入表,以便能够得到要求的结果的建议。在以前的迭代中,我对每个程序都有几十种不同的选择,但我发现这种方法完全没有用。所以我大大简化了可能的程序类型。但我仍然不明白如何使用这个输入来聚合数据。如果我太笨了,看不到它已经有可能得到结果,我正在寻找从现有的输入,请告诉我的方向。
问题tl:dr-我正在使用mysql中的当前输入表寻找可能的/可行的聚合吗?-如果没有,您建议对我的输入表进行什么样的修改如果是的话,请告诉我正确的方向。
编辑
尝试更详细地描述逻辑:
每个用户都可以有多个程序
每个程序都可以由用户在类型列中表示的部分中获取。
程序aaa在该行中只有以下输入选项init、1/2、1/3或full possible(我对此没有影响)。
其他程序有:1/2,2/2,1/3,2/3,3/3,full,init
因此,每个程序都可以有以下状态类型之一:init、1/2、1/3、2/3、full、return
伪代码:

For every program that user has:
 If there is only one type for a program then result = that type.   
 If there is more than one type of program: 
   check if there are any refund    
    if every program type has refund, then result = refund  
    if there are program type without refund, result = aggregated   
    if there are no refunds, then result = aggregated
7kjnsjlb

7kjnsjlb1#

SELECT user_id, program,
    CASE 
        WHEN COUNT(DISTINCT type) = 1 THEN MAX(type) -- one type, use that type
        WHEN SUM(more = 'refund') = COUNT(DISTINCT type) THEN 'refund'
        WHEN SUM(IF(LOCATE('/', type), SUBSTRING_INDEX(type, '/', 1), 0)) >= 3 THEN 'full'
        WHEN MAX(LOCATE('/', type)) > 0 THEN CONCAT(SUM(IF(LOCATE('/', type), SUBSTRING_INDEX(type, '/', 1), 0)), '/3')
        ELSE MAX(type)
    AS aggregated
FROM yourTable
GROUP BY user_id, program

演示

相关问题