MySQL:对表B中的每个成员,在表A中的行中减去两个值

时间:2014-03-10 21:48:57

标签: mysql sql

我用Java编写了这段代码,想知道我是否可以在SQL语句中更有效地完成它。

我有两张桌子。一个持有成员的数据,另一个持有他们的测量数据。

Members
 ID  | Name
 ----------
 001 | Mary
 002 | Jane
 003 | Anne


Measurements
  idMember | date       |  weight
  -------------------------------
  001      | 2013-06-21 |  65
  002      | 2013-06-23 |  68
  003      | 2013-06-21 |  75
  001      | 2013-09-20 |  64
  002      | 2013-06-21 |  70
  001      | 2014-01-18 |  62
  003      | 2013-06-21 |  74
  002      | 2013-06-21 |  69

我需要做的是找到总重量损失(或增加)。

这意味着查看每个成员并从第一个成员中减去最后一个测量值然后将总和相加。

谢谢!

3 个答案:

答案 0 :(得分:2)

select sum(s0.w - s1.w) as total_weight_loss
from (select idMember, max(weight) as w from Measurements m
      where m.date = (select min(date)  from Measurements n
                      where m.idMember = n.idMember)
      group by idMember) s0
join (select idMember, min(weight) as w from Measurements m
      where m.date = (select max(date)  from Measurements n
                      where m.idMember = n.idMember)
      group by idMember) s1
on s0.idMember = s1.idMember

修改

事实证明,还有一个Measurements.ID,所有与同一日期测量处理相关的困难都可以像这样完全避免:

select sum(s0.w - s1.w) as total_weight_loss
from (select idMember, weight as w from Measurements m
      where m.ID = (select min(ID) from Measurements n
                    where m.idMember = n.idMember)) s0
join (select idMember, weight as w from Measurements m
      where m.ID = (select max(ID) from Measurements n
                    where m.idMember = n.idMember)) s1
on s0.idMember = s1.idMember

答案 1 :(得分:1)

尝试:

select members.name,
       curr.date as curr_date,
       curr.weight as curr_weight,
       prev.weight as prev_weight,
       curr.weight - prev.weight as weight_change
  from members
  join measurements curr
    on members.id = curr.idmember
  join measurements prev
    on members.id = prev.idmember
 where prev.date = (select max(x.date)
                      from measurements x
                     where x.idmember = prev.idmember
                       and x.date < curr.date)

SQL小提琴:http://sqlfiddle.com/#!2/c16123/7/0

答案 2 :(得分:0)

试试这个

  select name, sum(t2.w - t1.w) as weight_changes,if(sum(t2.w - t1.w)<0,concat('Lost ',ABS(sum(t2.w - t1.w)),' Kg'),concat('Gained ',ABS(sum(t2.w - t1.w)),' Kg')) status
  from (select idMember, max(weight) as w from Measurements m
  where m.date = (select min(date)  from Measurements n
                  where m.idMember = n.idMember)
  group by idMember) t1
  join (select idMember, min(weight) as w from Measurements m
  where m.date = (select max(date)  from Measurements n
                  where m.idMember = n.idMember)
  group by idMember) t2
  on t1.idMember = t2.idMember
  join Members ON Members.id = t1.idMember
   Group by t1.idMember

DEMO HERE