2

我有这个代码:

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 级别的建议,我也会很高兴!

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

4

3 回答 3

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';

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

于 2013-03-28T11:06:28.647 回答
0

GROUP BY p1.value与 一起使用SUM

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;
于 2013-03-28T08:42:44.337 回答
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
于 2013-03-28T09:10:53.617 回答