需要在一个代码中添加多个运行总计列

时间:2017-02-14 21:28:59

标签: sql-server sql-server-2008-r2

我为一个列源创建了一个运行总计的列,但我需要来自不同列源的多个运行总计。我如何在一个代码中执行此操作?

;WITH RunTot AS
  (SELECT DISTINCT ROW_NUMBER()over(partition BY memberid
                                    ORDER BY OriginalSubmitDate,OriginalSubmitTime) AS ROW,
                   MemberID,
                   Convert(varchar(12),OriginalSubmitDate,101) AS 'OriginalSubmitDate',
                   Convert(varchar,OriginalSubmitTime,108) AS 'OriginalSubmitTime',
                   TotalDrugCostonClaim
   FROM dbo.Holly_QICRestack_Modified
   WHERE ClaimStatus <> 'X'
     AND MemberID = '01317453701')
SELECT ROW,
       MemberID,
       OriginalSubmitDate,
       OriginalSubmitTime,
       TotalDrugCostOnClaim,

  (SELECT Sum(TotalDrugCostOnClaim)
   FROM RunTot b
   WHERE b.memberid = a.memberID
     AND b.row <= a.row) AS RunTotal
FROM RunTot a

1 个答案:

答案 0 :(得分:0)

这样的事情应该有效

;WITH RunTot AS
  (SELECT DISTINCT ROW_NUMBER()over(partition BY memberid
                                    ORDER BY OriginalSubmitDate,OriginalSubmitTime) AS ROW,
                   MemberID,
                   Convert(varchar(12),OriginalSubmitDate,101) AS 'OriginalSubmitDate',
                   Convert(varchar,OriginalSubmitTime,108) AS 'OriginalSubmitTime',
                   TotalDrugCostonClaim
   FROM dbo.Holly_QICRestack_Modified
   WHERE ClaimStatus <> 'X'
     AND MemberID = '01317453701')
SELECT ROW,
       MemberID,
       OriginalSubmitDate,
       OriginalSubmitTime,
       TotalDrugCostOnClaim,   
  (SELECT Sum(TotalDrugCostOnClaim)
   FROM RunTot b
   WHERE b.memberid = a.memberID
     AND b.row <= a.row) AS RunTotal,
 (SELECT Sum(SomeOtherColumn)
   FROM RunTot b
   WHERE b.memberid = a.memberID
     AND b.row <= a.row) AS OtherRunTotal
FROM RunTot a