Group By上的更新

时间:2017-10-11 15:46:55

标签: mysql

这是数据:

Mbr_Rel_Id  Most_Recent COV_START_DATE  START_DATE
93698       NULL        2006-07-01      2006-07-01
93698       NULL        2006-07-01      2008-01-01
93698       NULL        2011-07-01      2011-07-01
93698       NULL        2014-07-01      2014-07-01
44726       NULL        2012-03-01      2012-03-01
44726       NULL        2012-03-01      2017-05-01
SELECT Mbr_Rel_Id,Most_Recent, COV_START_DATE, START_DATE
FROM tbl_mbr_cov 
WHERE (Mbr_Rel_Id, COV_START_DATE, START_DATE) 
IN 
( SELECT Mbr_Rel_Id, COV_START_DATE, MAX(START_DATE)
  FROM tbl_mbr_cov
GROUP BY 
tbl_mbr_cov.MBR_REL_ID,
tbl_mbr_cov.COV_START_DATE 
)

以上查询给出了我想要的结果。我在MBR_REL_ID和COV_START_DATE上进行分组,返回最近START_DATE的行。所以这些是结果:

Mbr_Rel_Id  Most_Recent COV_START_DATE  START_DATE
93698       NULL        2006-07-01      2008-01-01
93698       NULL        2011-07-01      2011-07-01
93698       NULL        2014-07-01      2014-07-01
44726       NULL        2012-03-01      2017-05-01

我需要在上面的查询结果中更新字段Most_Recent = 1。所以我的看起来就像这样:

Mbr_Rel_Id  Most_Recent COV_START_DATE  START_DATE
93698       NULL        2006-07-01      2006-07-01
93698       1           2006-07-01      2008-01-01
93698       1           2011-07-01      2011-07-01
93698       1           2014-07-01      2014-07-01
44726       NULL        2012-03-01      2012-03-01
44726       1           2012-03-01      2017-05-01

下面的更新查询会更新最顶层显示的所有记录,而不仅仅是每组最大值:

Update tbl_mbr_cov A
INNER JOIN (
SELECT Mbr_Rel_Id,Most_Recent, COV_START_DATE, START_DATE
FROM tbl_mbr_cov 
WHERE (Mbr_Rel_Id, COV_START_DATE, START_DATE) 
IN 
( SELECT Mbr_Rel_Id, COV_START_DATE, MAX(START_DATE)
  FROM tbl_mbr_cov
GROUP BY 
tbl_mbr_cov.MBR_REL_ID,
tbl_mbr_cov.COV_START_DATE 
) )B
ON B.MBR_REL_ID = A.MBR_REL_ID
SET A.Most_Recent = 1

如何构建更新以将Most_Recent = 1设置为上面最大组查询中的那些?

0 个答案:

没有答案