SQL连接表更低的日期和更低的ID

时间:2017-11-19 16:52:40

标签: mysql sql

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

START

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

REPEAT

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)当在REPEAT表中找到超过1个INSPECID时,请考虑较低日期的分数。

3)当匹配INSPECID且匹配日期而不是考虑REPEAT表中的较低ID时,ID 4和ID 8具有相同的日期和相同的INPECTID,但考虑ID 4得分为4。

2 个答案:

答案 0 :(得分:1)

使用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相同时的冲突,请使用CASE选择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

答案 1 :(得分:0)

这有点棘手。以下使用group_concat()技巧计算第一个和最后一个分数。然后将它们放入您想要的类别中:

select w.which, count(r.INSPECID)     
from (select 'DECREASING' as which union all
      select 'INCREASING' as which union all
      select 'EQUAL' as which
     ) w left join
     (select r.INSPECID,
             (substring_index(group_concat(score order by date), ',', 1) + 0) as first_score,
             (substring_index(group_concat(score order by date desc), ',', 1) + 1) as last_score
      from repeat r
      group by INSPECID
     ) r
     ON (last_score > first_score and w.which = 'INCREASING') or
        (last_score < first_score and w.which = 'DECREASING') or
        (last_score = first_score and w.which = 'INCREASING')
group by w.which;

请注意,第一个表格不是必需的。