sql server group由不同的列组成

时间:2016-07-21 20:56:26

标签: sql sql-server

我的数据看起来像这样

           Amount  Officer   Branch
             100       S1     B1
             200       S1     B2
             300       S1     B3
             100       S2     B1
             200       S2     B2
             300       S2     B3

我需要另一个专栏,可以显示官员的总数

           Amount  Officer   Branch  TotalByOfficer
             100       S1     B1       500
             200       S1     B2       500
             300       S1     B3       500
             100       S2     B1       900
             200       S2     B2       900
             600       S2     B3       900

有了这个,我可以使用having子句来过滤TotalByOfficer。 我如何完成这样的事情。

2 个答案:

答案 0 :(得分:2)

您只需在SUM()OVER PARTITION Officer执行:

Select  Amount,
        Officer,
        Branch,
        Sum(Amount) Over (Partition By Officer) As TotalByOfficer
From    YourTable

答案 1 :(得分:0)

SELECT amount, officer, branch, 
       SUM(amount) OVER (PARTITION BY officer) as TotalByOfficer
FROM Table

注意,你只能使用" HAVING"如果你使用的是我没有的群体。将其用作子查询并添加过滤器,如此

SELECT * 
FROM (
  SELECT amount, officer, branch, 
         SUM(amount) OVER (PARTITION BY officer) as TotalByOfficer
  FROM Table
) X
WHERE TotalByOfficer <> 500