日期:2014-05-18  浏览次数:20731 次

求语句。。。。。。。。
A表中有一下数据
  字段 AA 字段 BB 字段 CC
  X 0101 100
  X 0102 30
  T 0101 40
  G 0102 60
  F 0101 10
  F 0102 15
 

需要查询结果是
  字段 AA 字段 BB 字段 CC
  X 0101 100
  X 0102 0
  T 0101 40
  G 0102 60
  F 0101 10
  F 0102 0
  

说明:当两条记录中的AA字段相等的时候:
  字段BB如果等于0101,那么就返回字段CC的原值;
  字段BB如果等于0102,那么就返0值;
  AA值不相等的时候,返回CC的原值


如何写查询语句,请指点,万分感谢

------解决方案--------------------
SQL code

--> 测试数据:[test]
if object_id('[test]') is not null drop table [test]
create table [test]([AA] varchar(1),[BB] varchar(4),[CC] int)
insert [test]
select 'X','0101',100 union all
select 'X','0102',30 union all
select 'T','0101',40 union all
select 'G','0102',60 union all
select 'F','0101',10 union all
select 'F','0102',15

select [AA],[BB],
case when [BB]='0101' then [CC] 
when ([BB]='0101' or BB='0102') and (select COUNT(1) from test b where a.AA=b.AA)=1
then  CC else 0  end  [CC]
from test a
/*

AA    BB    CC
X    0101    100
X    0102    0
T    0101    40
G    0102    60
F    0101    10
F    0102    0
*/

------解决方案--------------------
探讨

这样查出来的结果第四行也为0了啊 ,实际上第四行是要原值的