我的MariaDb中有一个表,该表如下表所示,需要创建“组”列(请参见输出)。 如果KEY_A和KEY_B的组合按LOAD_DATE的顺序更改,则组会更改(请参见输出)。 我找不到合适的SQL来生成“组”列。
也许有人有一个想法如何在MariaDB中解决这个问题?
TestData:
CREATE OR REPLACE TABLE test AS
SELECT 'AAA' AS KEY_A,'A' AS KEY_B,DATE('2010-01-01') AS LOAD_DATE
UNION
SELECT 'AAA' AS KEY_A,'B' AS KEY_B,DATE('2010-01-02')
UNION
SELECT 'AAA' AS KEY_A,'A' AS KEY_B,DATE('2010-01-03')
UNION
SELECT 'AAA' AS KEY_A,'A' AS KEY_B,DATE('2010-01-04')
UNION
SELECT 'BBB' AS KEY_A,'C' AS KEY_B,DATE('2010-01-04')
UNION
SELECT 'CCC' AS KEY_A,'D' AS KEY_B,DATE('2010-01-04') ;
输出:
KEY_A; KEY_B; LOAD_DATE; group
AAA; A; 2010-01-01; 1
AAA; B; 2010-01-02; 2
AAA; A; 2010-01-03; 3
AAA; A; 2010-01-04; 3
BBB; C; 2010-01-04; 1
CCC; D; 2010-01-04; 1
答案 0 :(得分:0)
您的测试数据实际上写错了。
测试数据:
CREATE TABLE TestDB.test AS
SELECT 'AAA' AS KEY_A,'A' AS KEY_B, DATE('2010-01-01') AS LOAD_DATE FROM DUAL
UNION
SELECT 'AAA' AS KEY_A,'B' AS KEY_B, DATE('2010-01-02') AS LOAD_DATE FROM DUAL
UNION
SELECT 'AAA' AS KEY_A,'A' AS KEY_B, DATE('2010-01-03') AS LOAD_DATE FROM DUAL
UNION
SELECT 'AAA' AS KEY_A,'A' AS KEY_B, DATE('2010-01-04') AS LOAD_DATE FROM DUAL
UNION
SELECT 'BBB' AS KEY_A,'C' AS KEY_B, DATE('2010-01-04') AS LOAD_DATE FROM DUAL
UNION
SELECT 'CCC' AS KEY_A,'D' AS KEY_B, DATE('2010-01-04') AS LOAD_DATE FROM DUAL
;
答案 1 :(得分:0)
我认为这是一个孤岛问题。
您可以使用窗口函数解决此问题:
select t.*,
sum( case when key_b = prev_key_b then 0 else 1 end ) over (partition by key_a order by load_date) as grp
from (select t.*,
lag(key_b) over (partition by key_a order by load_data) as prev_key_b
from t
) t;