动态设置年份,同时按月显示总和

时间:2011-12-09 20:52:10

标签: sql-server

所以我想查询表格,它显示每月的成本总和,年份应该是动态的,我写了这个查询,但它没有总结成本。

SELECT *
FROM (
  SELECT TOP 100 2003 + ROW_NUMBER() OVER (ORDER BY PostingDate) AS Yr, SUM(Amount) as Total
  FROM table1
  GROUP BY PostingDate
  ) Years
WHERE Yr <= YEAR(GETDATE())

应该是

month  cost     year 
jan    12.00    2011
feb    10.00    2011

然后是2010年的另一个专栏。这可能吗

...

1 个答案:

答案 0 :(得分:0)

SELECT
 CASE
    WHEN DATEPART(month, PostingDate) = 1 then 'Jan',
    WHEN DATEPART(month, PostingDate) = 2 then 'Feb',
    WHEN DATEPART(month, PostingDate) = 3 then 'March',
    WHEN DATEPART(month, PostingDate) = 4 then 'April',
    WHEN DATEPART(month, PostingDate) = 5 then 'May',
    WHEN DATEPART(month, PostingDate) = 6 then 'Jun',
    WHEN DATEPART(month, PostingDate) = 7 then 'Jul',
    WHEN DATEPART(month, PostingDate) = 8 then 'Aug',
    WHEN DATEPART(month, PostingDate) = 9 then 'Sep',
    WHEN DATEPART(month, PostingDate) = 10 then 'Oct',
    WHEN DATEPART(month, PostingDate) = 11 then 'Nov',
 ELSE 'DEC' as [Month],
 SUM(Amount) as Total,
 DATEPART(year, PostingDate) as [Year]
FROM
  Table1
WHERE
  DATEPART(year, PostingDate) <= DATEPART(year, GETDATE())
GROUP BY
  DATEPART(year, PostingDate) as [Year],
  DATEPART(month, PostingDate) as [Month]

注意:在记事本中未经测试:/