获取其中列的最新行和总和

时间:2016-12-08 07:04:54

标签: sql-server

在我的表格中,我有三列amountdatememberID。现在我想将最新数量插入到表中,并且到目前为止插入的总金额总和。

我的查询就像这样

SELECT  amount , SUM(amount) as TotalAmount FROM [Transactions] 
WHERE memberid = 1629 Order By Date DESC

但这会引发像这样的错误

  

Msg 8120,Level 16,State 1,Line 1   “Transactions.amount”列在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

有谁可以指出我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

SELECT amount AS LatestAmount,
       (SELECT SUM(amount) FROM [Transactions]) AS TotalAmount
FROM [Transactions]
WHERE date = (SELECT MAX(date) FROM [Transactions])

请注意,如果超过一个最新金额的平局,上述查询将为每个捆绑交易生成一条记录。如果只需要一个结果,并且您使用的是SQL Server 2008或更高版本,则可以使用TOP(1)来限制单个结果:

SELECT TOP(1) amount AS LatestAmount,
       (SELECT SUM(amount) FROM [Transactions]) AS TotalAmount
FROM [Transactions]
WHERE date = (SELECT MAX(date) FROM [Transactions])

答案 1 :(得分:0)

只需添加Group by子句

SELECT  amount , SUM(amount) as TotalAmount FROM [Transactions] 
GROUP BY amount WHERE memberid = 1629 Order By Date DESC