0

我正在尝试用排名函数和按月分组的列求和,我的代码是

 select  dbo.UpCase( REPLACE( p.Agent_name,'.',' '))as Agent_name, SUM(convert ( float ,   
  p.Amount))as amount,   
  RANK() over( order by  SUM(convert ( float ,Amount )) desc ) as arank 
  from  dbo.T_Client_Pc_Reg p  
  group by   p.Agent_name ,p.Sale_status ,MONTH(Reg_date)
  having [p].Sale_status='Activated'

目前,我正在获取该列的所有总价值,而不是按月计算

Name  amount rank 
a     100    1
b     80     2
c     50     3

100 是到目前为止的总金额,但是,我想获得当前月份的总金额,而不是上个月的总金额..

4

1 回答 1

1

也许您只需要添加一个 WHERE 子句?这是一个小的重写,我认为通常效果更好。tempdb 中的一些设置:

USE tempdb;
GO

CREATE TABLE dbo.T_Client_Pc_Reg
(
  Agent_name VARCHAR(32),
  Amount INT,
  Sale_Status VARCHAR(32),
  Reg_date DATETIME
);

INSERT dbo.T_Client_Pc_Reg 
          SELECT 'a', 50, 'Activated', GETDATE()
UNION ALL SELECT 'a', 50, 'Activated', GETDATE()
UNION ALL SELECT 'b', 20, 'Activated', GETDATE()
UNION ALL SELECT 'b', 20, 'Activated', GETDATE()
UNION ALL SELECT 'b', 20, 'Activated', GETDATE()
UNION ALL SELECT 'b', 20, 'Activated', GETDATE()
UNION ALL SELECT 'b', 20, 'NotActivated', GETDATE()
UNION ALL SELECT 'c', 25, 'Activated', GETDATE()
UNION ALL SELECT 'c', 25, 'Activated', GETDATE()
UNION ALL SELECT 'c', 25, 'Activated', GETDATE()-40;

然后查询:

SELECT 
  Agent_name = UPPER(REPLACE(Agent_name, '.', '')),
  Amount = SUM(CONVERT(FLOAT, Amount)),
  arank = RANK() OVER (ORDER BY SUM(CONVERT(FLOAT, Amount)) DESC)
FROM dbo.T_Client_Pc_Reg
WHERE Reg_date >= DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP), 0)
  AND Reg_date <  DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP) + 1, 0)
  AND Sale_status = 'Activated'
GROUP BY UPPER(REPLACE(Agent_name, '.', ''))
ORDER BY arank;

现在清理:

USE tempdb;
GO
DROP TABLE dbo.T_Client_Pc_Reg;
于 2012-05-01T00:19:35.577 回答