日期:2014-05-17  浏览次数:20919 次

索尼DADC面试的一道题,求解!!!!!
题目大概是这样的:

某表:
tcode tname ttype tnum
1 A 1 100
1 A 1 500
1 B 1 200
1 B 2 600
2 A 3 400
2 A 3 700
2 B 1 400

想要获取这样的结果:
tcode tname tnum tstatus
1 A 600 未完成
1 B 800 完成中
2 A 1100 完成
2 B 400 未完成

tnum结果分组相加
注:分组中ttype若全为1,则tstatus为未完成
  若含有一个2,则tstatus为完成中
  若全为3,则tstatus为完成

回来后想了一会,用下列语句得出:
select tcode,
  tname,
  tnum,
  case
  when tid = 1 then
  '未完成'
  when tid = 3 then
  '完成'
  when tid like '%2%' then
  '完成中'
  else
  '异常'
  end tstatus
  from (select tcode,
  tname,
  sum(tnum) tnum,
  max(decode(ttype, 1, ttype, null)) ||
  max(decode(ttype, 2, ttype, null)) ||
  max(decode(ttype, 3, ttype, null)) tid
  from t_test
  group by tcode, tname
  order by tcode, tname);

感觉语句有些繁琐,不知道是否有其他简易点的方法?


------解决方案--------------------
对应的ttype都减去1,那么
sum(ttype)=0 ,未完成
sum(ttype)=count(*) 已完成
两者之外就算完成中

------解决方案--------------------
SELECT tcode,
tname,
decode(ttype,
1,
'未完成',
2,
'完成中',
3,
'完成',
NULL) status,
tsum
FROM (SELECT tcode,
tname,
MAX(ttype) ttype,
SUM(tnum) tsum
FROM sony
GROUP BY tcode,
tname);
------解决方案--------------------
[code=SQL][/code]select tcode,tname,sum(tnum),
2 case when sum(ttype)/count(*)=1 then '未完成'
3 when sum(ttype)/count(*)=3 then '完成'
4 else '完成中' end from t_test group by tcode,tname;
------解决方案--------------------
+1,思维不错
[Quote=引用:]

[code=SQL][/code]select tcode,tname,sum(tnum),
2 case when sum(ttype)/count(*)=1 then '未完成'
3 when sum(ttype)/count(*)=3 then '完成'
4 else '完成中' end from t_test group by tcode,tname;
[/Quote]