是否可以在执行连接时获得总和?

时间:2013-03-28 08:40:28

标签: sql oracle birt

我有这段代码:

select id,
p1.value as company,
p2.value as budget

FROM  process p

LEFT JOIN Param p1 on p1.ID = p.ID AND p1.NAME = 'Company'
LEFT JOIN Param p2 ON p2.ID = p.ID AND p2.NAME = 'Budget'

where type = 'Authorization';

我的公司很少。这里的示例结果如下:

Company      Budget

Goodis       10000
McDonalds    15000
Goodis       500
Goodis       100
Everest      100
McDonalds    1000
Everest      10000

我想要做的是获得每家公司的预算总和(我不能在where子句中分离公司,因为我需要整个数据,而且有很多公司)。我似乎很难在SQL中完成。我正在尝试做一个BIRT报告,所以,如果你有任何关于BIRT级别的建议,我也会非常高兴!

这是一种方法吗,或者我的尝试毫无意义?

3 个答案:

答案 0 :(得分:3)

我相信你想要一个分析函数:

select id, p1.value as company, p2.value as budget,
       sum(p2.value) over (partition by p1.value) as CompanyBudget
FROM  process p
LEFT JOIN Param p1 on p1.ID = p.ID AND p1.NAME = 'Company'
LEFT JOIN Param p2 ON p2.ID = p.ID AND p2.NAME = 'Budget'
where type = 'Authorization';

这将返回每行的总预算,但不会减少行数。

答案 1 :(得分:0)

GROUP BY p1.valueSUM

一起使用
select 
  p.value as company,
  COALESCE(SUM(p2.value), 0) as Totalbudget
FROM  Param AS p
LEFT JOIN process AS p1 ON p.ID = p1.ID AND p.NAME = 'Company'
LEFT JOIN process AS p2 ON p.ID = p2.ID AND p.NAME = 'Budget'
GROUP BY p.value;

答案 2 :(得分:0)

看看这是否有帮助 -

SELECT id, company, SUM(NVL(budget, 0)) AS budget
FROM
(
   SELECT id,
   p1.value AS company,
   p2.value AS budget
   FROM  process p
   LEFT JOIN Param p1 on p1.ID = p.ID AND p1.NAME = 'Company'
   LEFT JOIN Param p2 ON p2.ID = p.ID AND p2.NAME = 'Budget'
   WHERE TYPE = 'Authorization'
)
WHERE company IS NOT NULL
GROUP BY id, company