HELP,还是Group的问题,各位大神帮下忙!
现在我有一个记录商品交易的表:
id(int) name(nvchar) quantity(float) price(float) flagSepecil(bit) retreatId(int)
100 AAA 1 50.5 0 NULL
101 BBB 3 100 0 NULL
102 BBB -1 100 0 101
103 CCC 1 80 1 NULL
104 CCC 1 80 1 NULL
105 CCC 1 80 1 NULL
106 CCC -1 80 1 105
说明:商品分为两种(由flagSepecil区分,1表示特殊商品,这种商品每份在数据库中都是单独的一条记录,如上表中的103-105的CCC;0表示普通商品,这种商品记录多份在数据库中是合在一起的一条记录,如上表中的101的BBB,quantity为-的表示退货的记录,对应的退货的编号是retreatId中记录的,如上表中的102的retreatId为101,说明这条记录是101的退货记录,106的retreatId为105,说明是105的退货记录)。
现在在查询时希望能将退货记录与其相应的原纪录合并在一起,得到如下的表:
100 AAA 1 50.5 0 NULL
101 BBB 2 100 0 NULL
103 CCC 1 80 1 NULL
104 CCC 1 80 1 NULL
105 CCC 0 80 1 NULL
我前面因为没有这种特殊商品所以都是直接按照name进行group,然后将SUM(quantity)就好了,但是加了这个特殊商品后发现他把特殊商品也全部group在一起了,请问改如何处理呢???
[最优解释]
if OBJECT_ID('commodity') is not null drop table commodity
create table commodity(
id int identity(100,1),
name nvarchar(50),
quantity float,
price float,
flagSepecil bit,
retreatId int
)
insert into commodity(name,quantity,price,flagSepecil,retreatId)
select 'AAA',1,50.5,0,NULL union all
select 'BBB',3,100,0,NULL union all
select 'BBB',-1,100,0,101 union all
select 'CCC',1,80,1,NULL union all
select 'CCC',1,80,1,NULL union all
select 'CCC',1,80,1,NULL union all
select 'CCC',-1,80,1,105
select c.id,c.name,c.quantity+isnull(d.quantity,0) as quantity,c.price,c.flagSepecil,c.retreatId from commodity as c
left join commodity as d on c.id=d.retreatId
where c.quantity>0
/*结果
id name quantity price flagSepecil retreatId
100AAA150.50NULL
101BBB21000NULL
103CCC1801NULL
104CCC1801NULL
105CCC0801NULL
*/
--删除测试表
drop table commodity