0

我有一张桌子ZXC

select NAME, MONTH, YEAR, DEPT, MONTHVAL, YEARVAL from ZXC

该列MONTHVAL有一些值。我想根据名称、部门和月份的组合聚合一些行,并在YEARVAL列中显示聚合值。

例如,如果我有桌子

Name   Month  Year Dept Monthval  Yearval

BLAKE   Jan   2011 100   124.542    0 
KING    Feb   2011 200   234.542    0 
KING    Jan   2011 200   27764.464  0 
BLAKE   March 2011 100   0          0 
BLAKE   Feb   2011 400   0          0 
SCOTT   Jan   2011 500   24564.464  0 
KING    March 2011 200   1265.542   0 
KING    April 2011 200   1065.542   0 

然后我想看到结果

Name   Month  Year Dept Monthval  Yearval

BLAKE   Jan   2011 100  124.542    124.542
KING    Jan   2011 200  27764.464  27764.464  
SCOTT   Jan   2011 500  24564.464  24564.464 
KING    Feb   2011 200  234.542    27999.006 
BLAKE   Feb   2011 100  0          124.542 
KING    March 2011 200  1265.542   29264.548 
BLAKE   March 2011 100  0          124.542 
KING    April 2011 200  1065.542   30330.09
4

3 回答 3

1

What about this:

SELECT name
     , dept
     , year
     , SUM( monthval ) yearval
FROM   zxc
GROUP  BY name
        , dept
        , year;

This would produce a total of monthly values for each year. I am not really sure if this is what you needed, but looks like it to me.

You can make it even fancier by using ROLLUP() or CUBE() functions in GROUP BY functions (multiple level of aggregations).

于 2012-05-17T09:00:53.963 回答
0

听上去像:

select NAME,
       MONTH,
       YEAR,
       DEPT,
       MONTHVAL,
       SUM(MONTHVAL) OVER (PARTITION BY YEAR) YEARVAL
  from ZXC
于 2012-05-17T14:04:24.350 回答
0

根据您的输出,您似乎想要每个人的运行总数。基本上,以下查询显示了一个通用解决方案:

SELECT
  Name,
  Month,
  Year,
  Dept,
  Monthval,
  SUM(Monthval) OVER (PARTITION BY Name, Dept ORDER BY Year, Month) AS Yearval
FROM ZXC

但是 order by 可能存在问题Month,因为月份似乎在您的表中存储为名称,而不是数字。然后我会像这样更改上面的内容:

SELECT
  Name,
  Month,
  Year,
  Dept,
  Monthval,
  SUM(Monthval) OVER (
    PARTITION BY Name, Dept
    ORDER BY TO_DATE(Year || '-' || SUBSTR(Month, 1, 3), '-01', 'YYYY-MON-DD')
  ) AS Yearval
FROM ZXC
于 2012-05-23T07:28:12.447 回答