计算相同类型的两行之间的差异

时间:2014-09-11 15:48:49

标签: mysql sql

假设我有下表(见下文),我想找到" memsize"或" totalstorage"对于同一台机器(=相同的vmnaam值)已经改变。

ID  VMNaam  Memsize totalstorage dataentrytime
1      x      12         150         blabla
2      x      12         150         blabla
3      x      14         150         blabla
4      Y      12         150         blabla
5      Y      20         150         blabla
6      Y      18         150         blabla 

以下查询查找这些行

 SELECT    realTable.VMnaam,
            realTable.memsize,
            realTable.totalstorage

    FROM      vmresourcetest realTable
              LEFT OUTER JOIN (
                 SELECT   (ID+1) AS 'virtualId',
                          (ID) AS 'realId',
                          vmnaam AS 'vmnaamVirtual',
                          memsize AS 'virtualMemsize',
                          totalstorage AS 'virtualTotalstorage'
                 FROM     vmresourcetest
                 ORDER BY vmnaam
              ) virtual 
              ON virtual.virtualId = realTable.id and virtual.vmnaamVirtual = realTable.vmnaam
    where IFNULL((realTable.memsize - virtual.virtualMemsize), 0) <> 0 or IFNULL((realTable.totalstorage - virtual.virtualTotalstorage), 0) <> 0

但是,当机器行被加扰时,我的查询显然不再起作用,因为前一个机器条目的ID可能是另一台机器的ID

E.g

1 x blablabla
2 y blablalba
3 y blablabll
4 x blablbla

我想以某种方式想要将ID + 1更改为(从idtable中选择ID,其中id&gt; id),但这并不起作用。 关于如何解决我的问题的任何想法?

1 个答案:

答案 0 :(得分:0)

这应该让你前进:

SELECT curr.VMnaam,
       curr.memsize,
       curr.totalstorage

FROM   vmresourcetest curr LEFT JOIN   
       vmresourcetest nxt ON curr.id < nxt.id 
                    AND curr.vmnaam = curr.vmnaam
                    AND (curr.memsize != nxt.memsize 
                           OR curr.totalstorage != nxt.totalstorage)
AND NOT EXISTS ( -- there is no record between current and next record
         SELECT * 
         FROM vmresourcetest  
         WHERE id > curr.id AND id < nxt.id AND vmnaam = curr.vmnaam)