SQL-返回按年度分组的表中列的数字差异(ORACLE)

时间:2017-04-18 16:11:46

标签: sql oracle

我有两张表格如下:

资产表:

assetnum | depid
----------------
1        | eng
2        | ap
3        | cao
.        | .
.        | .
.        | .

AND

Meterreading Table:

assetnum | meterreading_date | reading
---------------------------------------
1        | 4/7/2017          |  50000
2        | 3/5/17            |  30000
3        | 1/15/17           |  10000
.        | .                 |  .
.        | .                 |  .
.        | .                 |  .

我正在努力做一个加入并每年使用每个资产。换句话说,我想得到 assetnum,depid,(该年度记录的最后一次读数 - 该年度记录的第一次读数)作为按年份分类的使用情况。

例如在上面的例子中,我将输出为

assetnum | depid  | usage
-------------------------
 1       |  eng   |   40000  (50000-10000)
 .       |   .    |   .
 .       |   .    |   .
 .       |   .    |   .

3 个答案:

答案 0 :(得分:2)

如果我理解正确,您只需要joingroup by

select mr.assetnum, a.depid,
       (max(usage) - min(usage)) as usage
from Meterreading mr join
     Asset a
     on mr.assetnum = a.assetnum
where meterreading_date >= date '2017-01-01 and
      meterreading_date < '2018-01-01'  -- unnecessary for the current year
group by mr.assetnum, a.depid; 

答案 1 :(得分:2)

鼓掌戈登的回应......只需从日期中提取年份,然后按其排除,取消地点。

SELECT mr.assetnum
     , a.depid
     , max(usage) - min(usage) as usage
     , to_char(meterreading_date,'YYYY') as Year
FROM Meterreading mr 
INNER join Asset a
  on mr.assetnum = a.assetnum
GROUP BY  mr.assetnum, a.depid, to_char(meterreading_date,'YYYY')

或者......使用extract vs to_char ...

SELECT mr.assetnum
     , a.depid
     , max(usage) - min(usage) as usage
     , extract(year from meterreading_date) as Year
FROM Meterreading mr 
INNER join Asset a
  on mr.assetnum = a.assetnum
GROUP BY  mr.assetnum, a.depid, extract(year from meterreading_date)

在这两种情况下,它都会获得每年的最小和最大使用量,并从最大值中减去最小值。它不是日期驱动,而是使用/年驱动。如果由于某种原因你在一年中的后期读数低于高......它可能无法返回预期的结果...真正的日期驱动我们需要得到最小/最大日期找到这些和从那里开始。

阅读的例子如下:

assetnum | meterreading_date | reading
---------------------------------------
1        | 7/5/2017          |  70000
1        | 6/1/2017          |  10000
1        | 5/7/2017          |  60000
1        | 4/7/2017          |  50000
1        | 3/5/17            |  30000
1        | 1/15/17           |  20000

那么2017年对于assetnum 1的使用率将是70000-10000或60000;但也许你想要70000-20000 = 50000 ......

答案 2 :(得分:0)

按年份分组的另一个答案:

SELECT reading.*, max_reading-min_reading used, depid
FROM 
  ( SELECT TRUNC(meterreading_date,'yyyy') meterreading_date, assetnum, MIN(reading) min_reading, MAX(reading) max_reading
    FROM METERREADING
    GROUP BY TRUNC(meterreading_date,'yyyy'), assetnum
  ) reading
    JOIN
  asset ON asset.assetnum=reading.assetnum