2

注意:我在 SO 上阅读了类似的线程,但对这个查询没有帮助。

我已经复制了以下与我的实际问题相似的代码。我必须使用这种语法,因为它已经在数据库中使用过,除非有令人信服的建议,否则这里的逻辑是错误的。

在我的实际问题中,此查询大部分时间都有效,但在特定时间失败。调查后发现问题出在

ISNULL(amount,0)

这是因为如果任何类别都有两个值 0,0 或两个值都为 null、null,ISNULL则使它们成为字符串,因此我得到

将数据类型 varchar 转换为 float 时出错

以下是我的带有注释的测试代码

create table #table1 (
id int not null primary key identity,
category varchar(10),
amount float null
)

insert into #table1 values('A',23)
insert into #table1 values('A',23)
insert into #table1 values('B',NULL)
insert into #table1 values('B',0)
insert into #table1 values('C',NULL)
insert into #table1 values('C',NULL)
insert into #table1 values('D',0)
insert into #table1 values('D',0)

select * from #table1 -- works

select category, sum1  -- works
 from 
(select category, SUM(Round(ISNULL(amount,0),0)) as Sum1 from #table1
group by category)  D

select category, sum2 = -- does not work
case Sum1
    when 'A' then Sum1 * 1   -- my problem is here
    when 'B' then Sum1 * 2   -- this is the logic in my actual code
    when 'C' then Sum1 * 3   -- would like to make this query work
    when 'D' then Sum1 * 4
    else Sum1
end 
 from 
(select category, SUM(Round(ISNULL(amount,0),0) ) as Sum1 from #table1
group by category)  D

我究竟做错了什么?

4

2 回答 2

3

您的案例陈述不应该是“案例类别”而不是“案例总和1”吗?

如果您更改它,查询将按预期工作。

于 2012-01-17T14:18:10.633 回答
2

您的案例需要查看类别而不是 sum1

select category, sum2 = -- does not work
case category
    when 'A' then Sum1 * 1   -- my problem is here
    when 'B' then Sum1 * 2   -- this is the logic in my actual code
    when 'C' then Sum1 * 3   -- would like to make this query work
    when 'D' then Sum1 * 4
    else Sum1
end 
 from 
(select category, SUM(Round(ISNULL(amount,0),0) ) as Sum1 from #table1
group by category)  D
于 2012-01-17T14:19:02.187 回答