SQL从日期范围内的同一表中的不同记录中获取多个项目的总和(ORACLE)
Posted
技术标签:
【中文标题】SQL从日期范围内的同一表中的不同记录中获取多个项目的总和(ORACLE)【英文标题】:SQL to get the sum of several items from different records in the same table within date range(ORACLE) 【发布时间】:2016-12-19 17:12:19 【问题描述】:我有一个如下架构。我想运行以下查询:
获取所有资产、描述、总成本(来自资产表)、其驱动程序、其 polclass、其经理(来自资产规范)和(所有增量的总和)作为使用日期范围的日期范围可以指定。例如,在这里我们可以指定从 2015 年 11 月 2 日到 2016 年 1 月 30 日,我们应该得到 delta 的总和作为使用量,所以记录看起来像这样
ASSETNUM|LOCATION|DESCRIPTION|TOTALCOST|DRIVER|POLCLASS|MANAGER|USAGE
----------------------------------------------------------------------
12345 | HERE | SEDAN |30000 |JOHN | SPORT | JOE | 828(300+78+450)
99999 | . | .........................................
ASSET:
ASSETNUM | LOCATION | DESCRIPTION | TOTALCOST
---------------------------------------------
12345 | HERE | SEDAN |30000
99999 | THERE | SUV |50000
. | . |. |.
ASSETSPEC:
ASSETNUM | ASSETATTRID | ALNVALUE
---------------------------------
12345 | DRIVER | JOHN
12345 | POLCALSS | SPORT
12345 | MANAGER | JOE
99999 | DRIVER | Greg
99999 | POLCLASS | SPORT
99999 | . | .
METERREADING:
ASSETNUM | DELTA | Reading Date
---------------------------------
12345 | 78 | 1/30/2016
12345 | 450 | 12/9/2015
12345 | 300 | 11/2/2015
我想一遍又一遍地加入表格以获取驱动程序、管理器和 polclass,但我不知道如何获得日期范围内的增量总和。这就是我的查询的样子
SELECT V.ASSETNUM,
drivers.ALNVALUE AS Driver,
manager.ALNVALUE AS Manager,
V.DESCRIPTION AS ASSET_DESC,
V.LOCATION,
MAXIMO.LOCATIONS.DESCRIPTION AS Location_description,
V.TOTALCOST,
polclass.ALNVALUE AS POLICY_CLASS,
FROM MAXIMO.ASSET V
INNER JOIN MAXIMO.ASSETSPEC drivers
ON V.ASSETNUM = drivers.ASSETNUM
AND drivers.ASSETATTRID = 'DRIVER'
INNER JOIN MAXIMO.ASSETSPEC polclass
ON V.ASSETNUM = polclass.ASSETNUM
AND polclass.ASSETATTRID = 'POLCLASS'
INNER JOIN MAXIMO.ASSETSPEC manager
ON V.ASSETNUM = manager.ASSETNUM
AND manager.ASSETATTRID = 'MANAGER'
INNER JOIN MAXIMO.LOCATIONS
ON MAXIMO.LOCATIONS.LOCATION = V.LOCATION
INNER JOIN MAXIMO.METERREADING
ON MAXIMO.METERREADING.ASSETNUM = V.ASSETNUM
【问题讨论】:
您可以PIVOT
assetspec 表将数据填充为每个assetnum 的列,而不是必须加入表3 次,fwiw。您将需要一个 SUM()
聚合查询来获得您所追求的总数。
@Boneist 谢谢。你能把你所指的sql代码提供给我吗?
你可以找到一些有用的信息here
【参考方案1】:
试试这个:
select assetnum,location,
description,totalcost,
manager,polcalss,driver,
sum(delta) total_delta from
(select * from (
select a.assetnum,
a.location,
a.description,
a.totalcost,
b.assetattrid,
b.alnvalue,
m.delta
from asset a inner join assetspec b on a.assetnum = b.assetnum
inner join meterreading m on a.assetnum = m.assetnum
where m.reading_date between
to_date('1/30/2015','mm/dd/yyyy')
and to_date('1/30/2016','mm/dd/yyyy')
)
pivot
(max(alnvalue) for
(assetattrid) in ('manager' as manager,
'polcalss' as polcalss,
'driver' as driver))
)
group by assetnum,location,description,
totalcost,manager,polcalss,driver;
【讨论】:
你能解释一下为什么我们必须在那里使用 max 函数吗?谢谢。 @jax 想想看。对于给定的assetnum
,经理可以有很多行,但输出中只有一个经理列。透视查询需要一个聚合函数来根据这些行选择值。可能是COUNT
、SUM
等。以上是关于SQL从日期范围内的同一表中的不同记录中获取多个项目的总和(ORACLE)的主要内容,如果未能解决你的问题,请参考以下文章
如何在从多个表中获取多行的同时删除 sql JOIN 中的重复项