如何计算SUM YTD格式

时间:2014-08-21 07:38:13

标签: sql-server-2008

我有桌面付款(实际有大约100k记录,不同类别,客户等):

Client      Dt          Amt  Category
  1       201312        10       Tax
  1       201401        10       Tax
  1       201405        10       Tax
  1       201406        10       Tax
  2       201311        10       Tax

我想为每个客户制作类别税的累计金额YTD。所以结果将是这样的:

Client      Dt          Amt  Category
  1       201312        10       Tax
  1       201401        10       Tax
  1       201405        20       Tax
  1       201406        30       Tax
  2       201311        10       Tax

谢谢

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT a.Client, a.Dt, SUM(b.Amt) AS Amt, a.Category
FROM payments a
JOIN payments b ON b.Client = a.Client
 AND b.Category = a.Category
 AND b.Dt <= a.Dt
 AND YEAR(b.Dt) = YEAR(a.Dt)
WHERE a.Category = 'Tax'
GROUP BY a.Client, a.Dt, a.Category