日期:2014-05-16  浏览次数:20759 次

数据分组查询问题求解
表结构如下:
FNO FName FJD FMoney
1 aa J 500
1 aa J 300
1 aa D 800
2 bb J 500
2 bb J 500
2 bb D 800
3 cc J 500
3 cc D 300

根据每组数据的J和D来判断金额是否持平;将J,D不持平的组数据查询出来,希望结果是:
2 bb J 500
2 bb J 500
2 bb D 800
3 cc J 500
3 cc D 300
求解;谢谢!

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

with T as (
select 1 FNO, 'aa' FName, 'J' FJD, 500 FMoney From dual union all
select 1, 'aa', 'J', 300 From dual union all
select 1, 'aa', 'D', 800 From dual union all
select 2, 'bb', 'J', 500 From dual union all
select 2, 'bb', 'J', 500 From dual union all
select 2, 'bb', 'D', 800 From dual union all
select 3, 'cc', 'J', 500 From dual union all
select 3, 'cc', 'D', 300 From dual)
SELECT * 
FROM T
WHERE T.FNO IN  
  (SELECT FNO 
  FROM (select FNO,DECODE(FJD,'J',FMoney,FMoney * -1) FMoney2 from T) 
  GROUP BY FNO 
  HAVING SUM(FMoney2) <> 0);