簡體   English   中英

MySQL-子查詢/ JOIN同一表的不同修訂項目

[英]MySQL - Subquery / JOIN same table different revision items

我有這種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

有任何想法嗎? 非常感謝

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

您必須為max(case when data_field_id=X then value end) data_record_id_X的每個值重復max(case when data_field_id=X then value end) data_record_id_X

步驟1: 每組只選擇一行
使用group_concatsubstring_index獲得data_record_revision_id的最后一個值

setp 2: 將行轉置為列
將data_field_id轉置為列

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM