+ -
当前位置:首页 → 问答吧 → SQL子查询错误,急!!

SQL子查询错误,急!!

时间:2011-12-07

来源:互联网

ALTER proc [dbo].[proc_getZhanDianShuJuData1]
 
  @stime varchar(200),--起始时间从
  @etime varchar(200),--至
  @start1 varchar(200)--终止时间从,
  @end1 varchar(200)--至
as


declare @dian1 decimal(18,2),@dian2 decimal(18,2),@liuliang1 decimal(18,2),@liuliang2 decimal(18,2)

set @dian1=(select sum(UsePower) from History where Testtime>=@stime and Testtime<=@etime group by StationName )
set @dian2=(select sum(UsePower) from History where Testtime>=@start1 and Testtime<=@end1 group by StationName )
set @liuliang1=(select sum(Alltotalrunning) from History where Testtime>=@stime and Testtime<=@etime group by StationName)
set @liuliang2=(select sum(Alltotalrunning) from History where Testtime>=@start1 and Testtime<=@end1 group by StationName)
select distinct Stationinfo.StationName as 站名,@dian1 as 起始电量,@dian2 as 终止电量,@liuliang1 as 起始累计流量,@liuliang2 as 终止累计流量,
@dian2-@dian1 as 用电量,@liuliang2-@liuliang1 as 用水量,Convert(decimal(18,2),(@dian2-@dian1)/(@liuliang2-@liuliang1)) as 吨水耗电 from History,Stationinfo
where Testtime between @stime and @end1 and History.StationName=Stationinfo.Agreement group by Stationinfo.Agreement,Stationinfo.StationName

上面是我写的存储过程,我在子查询里加入group by分组后查询不出数据来。然后报错:子查询返回的值不止一个。当子查询跟随在 =、!=、<、<=、>、>= 之后,或子查询用作表达式时,这种情况是不允许的。

作者: yufei_yuxuan   发布时间: 2011-12-07

SQL code
set @dian1=(select sum(UsePower) from History where Testtime>=@stime and Testtime<=@etime group by StationName )


這樣寫法錯誤,有多個StationName時會出現錯誤

比如:這樣循環賦值
SQL code
select  @dian1=sum(UsePower) from History where Testtime>=@stime and Testtime<=@etime group by StationName

作者: roy_88   发布时间: 2011-12-07

set @dian1=(select sum(UsePower) from History where Testtime>=@stime and Testtime<=@etime group by StationName )
set @dian2=(select sum(UsePower) from History where Testtime>=@start1 and Testtime<=@end1 group by StationName )
set @liuliang1=(select sum(Alltotalrunning) from History where Testtime>=@stime and Testtime<=@etime group by StationName)
set @liuliang2=(select sum(Alltotalrunning) from History where Testtime>=@start1 and Testtime<=@end1 group by StationName)

括号里面的子查询group by分组后返回多行记录,set语句不知道你要把哪一行的sum结果给变量赋值,所以就出错了

作者: pengxuan   发布时间: 2011-12-07

所以你要保证给用子查询给变量赋值时子查询只能返回一行记录

作者: pengxuan   发布时间: 2011-12-07

子查询返回的值不止一个。当子查询跟随在 =、!=、<、<=、>、>= 

这样的话子查询可能出现多个值 一般可以用IN 解决

作者: fredrickhu   发布时间: 2011-12-07

select @dian1=sum(UsePower) from History where Testtime>=@stime and Testtime<=@etime group by StationName

这样可以查询出来,但是查询出来后的数据都是一样的。没有按分组显示.

作者: yufei_yuxuan   发布时间: 2011-12-07