枢轴外的聚合函数

时间:2014-01-09 07:44:36

标签: sql sql-server-2008

是否可以在枢轴之外使用聚合函数?我试图这样做。在这里,我编写一个查询,其中包含Pivot之外的聚合函数,它不起作用。

select id,**sum(num),**jan,feb
from ( select id, num, month(date) as date, val
......
.......
)p
pivot(sum(val) for date in ([jan],[feb])) as pivotanble

如果我省略 sum(num) 或仅使用num,则不然。什么是解决方案?

初始输入

      id   date       num    val

       1---2001.06.03--2------3

       2---2002.02.05--10-----5

       3----2002.02.09---4----2

预期

          JAN FEB MAR... year

           0--- 8 --0  -- 14

年将在这里输入年份= 2002

2 个答案:

答案 0 :(得分:0)

您能否参考以下网址

Pivoting Without Aggregation

答案 1 :(得分:0)

当然,您可以将所有月度值相加以获得年度值:

SELECT
  id,
  Jan,
  Feb,
  ...
  Year = Jan + Feb + ...
FROM (
  SELECT
    id,
    num,
    date = LEFT(DATENAME(MONTH, date), 3)
  FROM ...
  WHERE ...
) AS s
PIVOT (
  SUM(num)
  FOR date IN (Jan, Feb, ...)
) AS p
;

但您也可以使用SUM() OVER ()预先在子选择中计算年度值:

SELECT
  id,
  Jan,
  Feb,
  ...
  Year
FROM (
  SELECT
    id,
    num,
    date = LEFT(DATENAME(MONTH, date), 3),
    Year = SUM(num) OVER (PARTITION BY LEFT(DATENAME(MONTH, date), 3))
  FROM ...
  WHERE ...
) AS s
PIVOT (
  SUM(num)
  FOR date IN (Jan, Feb, ...)
) AS p
;