我有这种mysql表:
data_store_id data_field_id data_record_id data_record_revision_id value
13992 70 705 2332 fraus
13993 71 705 2332 john
13994 86 705 2332
13995 87 705 2332 01/01/2020
13996 88 705 2332 1
13997 84 705 2332 10/10/2020
13998 85 705 2332
13999 81 705 2332 1
14000 82 705 2332
14001 83 705 2332
14002 71 705 2333 nick
14003 87 705 2333 10/10/2015
14004 84 705 2333
14005 71 705 2334
14006 71 705 2335 peter
14007 86 705 2336 01/01/2012
14008 70 706 2337 liquorice
14009 71 706 2337 antony
14010 86 706 2337
14011 87 706 2337 02/02/2150
14012 88 706 2337 1
14013 84 706 2337 01/01/1987
14014 85 706 2337
14015 81 706 2337 1
14016 82 706 2337
14017 83 706 2337
14018 71 706 2338 dave
14019 87 706 2338 20/01/2011
14020 84 706 2338
14021 71 706 2339
14022 71 706 2340 winter
14023 86 706 2341 01/01/2012
我正在尝试编写一个查询来解决: 对于每个“data_record_id”,对于每个“data_field_id”,最后“data_record_revision_id”的“值”。 例如, 我需要得到类似的东西:
data_record_id data_field_id_70 data_field_id_71 data_field_id_87
705 fraus peter 10/10/2015
706 liquorice winter 20/01/2011
任何想法? 非常感谢
答案 0 :(得分:1)
select
data_record_id,
max(case when data_field_id=70 then value end) data_record_id_70,
max(case when data_field_id=71 then value end) data_record_id_71,
max(case when data_field_id=87 then value end) data_record_id_87
from
(select data_field_id,data_record_id,substring_index(group_concat(value order by data_record_revision_id desc separator '|'),'|',1) value
from your_table
group by data_record_id,data_field_id
) s
group by data_record_id
您必须为data_field_id
的每个值重复max(case when data_field_id=X then value end) data_record_id_X
第1步:select only one row per group
使用group_concat
和substring_index
setp 2:transpose rows to columns
将data_field_id转置为列