如何编写此查询?

时间:2011-04-27 04:46:21

标签: sql sql-server tsql sql-server-2008

我想通过名称检索所有信息以及金额总和,因此我将此查询用于此目的。

select SUM(Amount)as total,RecieptNo,Name,UniqueId,Date,Amount,LateFee,Other from Amount where Name='Shaikh'

但发生此错误。 专栏' Amount.RecieptNo'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。  所以请帮助我。

4 个答案:

答案 0 :(得分:4)

Select RecieptNo, Name
    , UniqueId, Date
    , Amount
    , LateFee, Other 
    , ( Select Sum( A1.Amount )
        From Amount As A1
        Where A1.Name = A.Name ) As Total
From Amount As A
Where Name='Shaikh'

SQL Server 2005 +中提供的另一种选择:

Select RecieptNo, Name
    , UniqueId, Date
    , Amount
    , LateFee, Other 
    , Sum( Amount ) Over( Partition By Name ) As Total
From Amount As A
Where Name='Shaikh'

答案 1 :(得分:1)

使用SUM()等聚合SQL函数时,必须使用GROUP BY子句。下面的例子证明了这一点。但这可能不是解决查询的最理想方法。我所做的是添加一个group by子句,其中包括除SUM之外选择的所有列。例如:

    select RecieptNo, Total, UniqueId, Date, Amount, LateFee, Other SUM(Amount)as total  from 
Amount where Name='Shaikh' group by RecieptNo, Total, UniqueId, Date, Amount, LateFee, Other

答案 2 :(得分:1)

select SUM(Amount)as total,RecieptNo,Name,UniqueId,Date,Amount,LateFee,Other from Amount
group by RecieptNo,Name,UniqueId,Date,Amount,LateFee,Other having Name='Shaikh'

答案 3 :(得分:0)

您需要分组

select SUM(Amount)as total,Name from Amount where Name='Shaikh' group by Name

如果您想在选择列表中添加其他内容,则需要在group by子句中添加此字段,否则会出错