我有以下两张桌子
开始和重复
开始

INSPECID=======SCORE
1--------------3
2--------------1
3--------------4

重复
ID========INSPECID========SCORE========DATE
1---------1---------------9------------12/01/2016
2---------1---------------1------------11/01/2016
3---------2---------------2------------29/01/2016
4---------2---------------4------------01/01/2016
5---------2---------------3------------22/01/2016
6---------2---------------5------------02/01/2016
7---------2---------------1------------11/01/2016
8---------2---------------1------------01/01/2016
9---------3---------------1------------02/01/2016
10--------3---------------2------------09/01/2016

我期望如下
INCREASED------1
DECREASED------2
EQUAL----------0

规则
1)通过INSPECID连接表
2)当在重复表中发现超过1个INSPECID时,考虑较低日期的得分。
3)当INSPECID匹配且日期匹配时,考虑重复表中较低的ID,因此ID 4和ID 8具有相同的日期和相同的INPECTID,但考虑ID 4的得分为4。

最佳答案

使用REPEAT表进行自连接以选择最早的行

select s.*,a.*
from `START` s
join `REPEAT` a on s.INSPECID = a.INSPECID
left join `REPEAT` b on a.INSPECID = b.INSPECID
and case when a.DATE = b.DATE
         then a.ID > b.ID
         else a.DATE > b.DATE
     end
where b.INSPECID is null

当INSPECID和DATE是同一个用例时选择ID最低的行时发生冲突
Demo
为所需结果集更新
select t.result,count(t1.result) cnt
from (
      select 'Increased' result
      union
      select 'Decreased' result
      union
      select 'Equal' result
) t
left join (
select s.score,a.id,a.DATE,
case when s.SCORE > a.SCORE
     then 'Increased'
     when s.SCORE < a.SCORE
     then 'Decreased'
     else 'Equal'
end result
from `START` s
join `REPEAT` a on s.INSPECID = a.INSPECID
left join `REPEAT` b on a.INSPECID = b.INSPECID
and case when a.DATE = b.DATE
         then a.ID > b.ID
         else a.DATE > b.DATE
     end
where b.INSPECID is null
) t1 using(result)
group by t.result

Demo

关于mysql - SQL连接表的较低日期和较低ID,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47379402/

10-11 02:22