有2个表:
TBL_WATER_RECORD即加水记录表,可能有成千上万行,包含字段WR_GUN_NUMBER即水枪号,为smallint类型
包含字段 WR_WEIGHT 即为加水的重量
表格如下
WR_GUN_NUMBER(smallint类型) WR_WEIGHT(int类型)
1 1580
1 790
3 800
4 900
2 1000
和TBL_WATERCAN即 水箱表,每个水箱对应多支不同的水枪号.
包含字段WC_WATERCAN_NUM即水箱号,smalint类型.
包含字段WC_GUN_NUM 即水枪号,可以有多支水枪,VARCHAR(50)类型
表格如下
WC_WATERCAN_NUM(smallint类型) WC_GUN_NUM(varchar类型)
1 1,3,4
2 2
3 5,6
现在我想求1号水箱对应的水枪一共加水的重量.
我的语句如下:
SELECT sum (WR_WEIGHT) FROM TBL_WATER_RECORD where charindex(','+rtrim(1)+',',','+(select top 1 WC_GUN_NUM from TBL_WATERCAN order by WC_WATERCAN_NUM)+',')>0
这条语句把 2号水枪的加水重量也累加到一起了,请问如何解决
------解决方案--------------------
create table TBL_WATER_RECORD(WR_GUN_NUMBER smallint,WR_WEIGHT int)
insert into tbl_water_record
select 1,1580 union all
select 1,790 union all
select 3, 800 union all
select 4, 900 union all
select 2,1000
create table TBL_WATERCAN(WC_WATERCAN_NUM smallint,WC_GUN_NUM VARCHAR(50))
insert into TBL_WATERCAN
select 1,'1,3,4' union all
select 2,'2' union all
select 3,'5,6'
go
select a.WC_WATERCAN_NUM,sum(b.WR_WEIGHT)ww
from TBL_WATERCAN a inner join TBL_WATER_RECORD b on charindex(','+ltrim(b.WR_GUN_NUMBER)+',',','+a.WC_GUN_NUM+',')>0
group by a.WC_WATERCAN_NUM