【发布时间】:2018-01-09 15:58:24
【问题描述】:
当我运行这个查询时:
SELECT [id],[amount],sum(amount) as Total
FROM transaction
where id='035'
group by id, amount
我得到了一些类似的结果
id amount Total
035 -55115.24 -55115.24
035 -2126.14 -2126.14
但是,当我尝试获取总数(对于 amount 列)时,使用此查询;
select id, count(*) as howMany, sum(amount) as Total
from transaction
where id='035'
group by id
order by count(*) desc
我得到了这些结果。
id howMany Total
035 2 0.00
我希望得到
id howMany Total
035 2 -057241.38
我试图简化查询,不计算,只是为了检查总和是否有效
select id, sum(amount) as Total
from transaction
where id='035'
group by id
但这又给了我 0 作为我的总数
id Total
035 0.00
我也在数量列中具有正值但行为相同的 id 上尝试过此操作。
为了澄清,我想要整个表中每个 id 的 amount 列中的值的总和,而不仅仅是每一行,但在 SQL 中使用 SUM 函数时我只得到零.
我注意到的另一件事是,id 列是 nvarchar,而不是表的 ID/键。这是一个旧数据库,出于某种原因,它倾向于将 nvarchars 链接到主键之上。我无法更改表结构。
架构
CREATE TABLE [dbo].[transaction](
[trindex] [int] IDENTITY(1,1) NOT NULL,
[id] [varchar](15) NULL,
[date] [datetime] NULL,
[amount] [money] NULL,
[acct] [varchar](20) NULL
)
【问题讨论】:
-
您是在 SQL Server Management Studio 中还是通过应用程序运行此查询?我的第一个猜测是应用程序正在更改值。
-
我正在通过 SSMS 运行它。应用程序不会更改这些值
-
从一个简单的 sql 中得到什么:SELECT [id],[amount] FROM transaction where id='035' and what datatype is amount?
-
如果你运行 SELECT SUM(CAST(amount AS DECIMAL(18,6))) FROM TRANSACTION WHERE id='035' 会有什么结果?
-
我猜可能是 2005 年,尝试在求和之前转换为数字:select id, SUM(amount), SUM(convert(numeric(18,2), amount))
标签: sql sql-server tsql sql-server-2005