0

假设我们有一个表,我们想要对 Expend 列进行求和,以便求和仅将相同 Week_Name 的值相加。

SN  Week_Name  Exp  Sum
--  ---------  ---  ---
1   Week 1     10   0
2   Week 1     20   0
3   Week 1     30   60
4   Week 2     40   0
5   Week 2     50   90
6   Week 3     10   0

我假设我们需要“按”Week_Name 排序,然后将前一个 Week_Name(上一行)与当前行 Week_name(当前行)进行比较。
如果两者相同,则在 SUM 列中输入零。

如果不相同,则添加所有支出,其中 Week_Name = Week_Name(Previous row) 并放在 Sum 列中。最终输出应如上表所示。

非常感谢任何有关如何在 T-SQL 中实现此目的的帮助。

4

2 回答 2

0

我不确定为什么您的 SN=6 行是 0 而不是 10。您真的不想要上周的总和吗?如果有上周的总数是可以的,那么你可能想要这样的东西:

;WITH CTE AS (
  SELECT Week_Name,SUM([Expend.]) as SumExpend
  ,MAX(SN) AS MaxSN
  FROM T
  GROUP BY Week_Name
  )
SELECT T.*,CASE WHEN T.SN = CTE.MaxSN THEN SumExpend
           ELSE 0 END AS [Sum]
FROM T
JOIN CTE on CTE.Week_Name = T.Week_Name

根据评论中希望在 SUM 中计算总和的要求,您可以尝试以下操作:

;WITH CTE AS (
SELECT Week_Name, MAX(SN) AS MaxSN
FROM T
GROUP BY Week_Name
)
SELECT T.SN, T.Week_Name,T.Exp, 
CASE WHEN T.SN = CTE.MaxSN THEN
(SELECT SUM(EXP) FROM T T2 
 WHERE T2.SN <= T.SN) ELSE 0 END AS [SUM]
FROM T
JOIN CTE ON CTE.Week_Name = T.Week_Name
ORDER BY SN
于 2012-06-02T06:37:12.017 回答
0

好的,我最终能够解决这个问题,赞美耶稣!如果你想要我上面给出的确切表格,你可以使用下面 GilM 的回复,它是完美的。如果您希望您的表有运行累积,即第 3 行应该有 60,第 5 行应该有 150,第 6 行 160 等。然后,您可以使用下面的代码:

USE CAPdb 
IF OBJECT_ID ('dbo.[tablebp]') IS NOT NULL
DROP TABLE [tablebp] 

GO
CREATE TABLE [tablebp] (
    tablebpcCol1 int PRIMARY KEY
  ,tabledatekey datetime
  ,tableweekname varchar(50)
  ,expenditure1 numeric
  ,expenditure_Cummulative numeric
)   

INSERT INTO [tablebp](tablebpcCol1,tabledatekey,tableweekname,expenditure1,expenditure_Cummulative)
SELECT b.s_tablekey,d.PK_Date,d.Week_Name,
SUM(b.s_expenditure1) AS s_expenditure1,
SUM(b.s_expenditure1) + COALESCE((SELECT SUM(s_expenditure1)
    FROM source_table bs JOIN dbo.Time dd ON bs.[DATE Key] = dd.[PK_Date]
    WHERE dd.PK_Date < d.PK_Date),0)
FROM source_table b
INNER JOIN dbo.Time d ON b.[Date key] = d.PK_Date 
GROUP BY d.[PK_Date],d.Week_Name,b.s_tablekey,b.s_expenditure1
ORDER BY d.[PK_Date]

;WITH CTE AS ( 
   SELECT tableweekname
   ,Max(expenditure_Cummulative) AS Week_expenditure_Cummulative
   ,MAX(tablebpcCol1) AS MaxSN 
FROM [tablebp] 
GROUP BY tableweekname 
) 
SELECT [tablebp].*
,CASE WHEN [tablebp].tablebpcCol1 = CTE.MaxSN THEN Week_expenditure_Cummulative
       ELSE 0 END AS [RunWeeklySum]
FROM [tablebp]
JOIN CTE on CTE.tableweekname = [tablebp].tableweekname
于 2012-06-02T23:53:35.817 回答