有一张表aa:
字段 a b
2009 胜
2009 败
2009 胜
2008 胜
2008 败
希望查找输出每一年胜利和失败的次数比如:
2009 2 1
2008 1 1
请教大侠们sql语句
------解决方案--------------------
- SQL code
with t1 as (select '2009' a,'胜' b from dual union allselect '2009' a,'败' b from dual union allselect '2009' a,'胜' b from dual union allselect '2008' a,'胜' b from dual union allselect '2008' a,'败' b from dual)select a 年份,sum(decode(b,'胜',1,0)) 胜,sum(decode(b,'败',1,0)) 败from t1group by a 年份 胜 败----------------------------1 2009 2 12 2008 1 1
------解决方案--------------------
- SQL code
CREATE TABLE T169( YEAR VARCHAR2(10), RESULT VARCHAR2(2));-- INSERT INTO T169 VALUES('2009', '胜');INSERT INTO T169 VALUES('2009', '败');INSERT INTO T169 VALUES('2009', '胜');INSERT INTO T169 VALUES('2008', '败');INSERT INTO T169 VALUES('2008', '胜');方法一:SELECT YEAR, (SELECT COUNT(RESULT) FROM T169 c WHERE RESULT='胜' AND t.year =c.year)胜 , (SELECT COUNT( RESULT) FROM T169 c WHERE RESULT='败' AND t.year =c.year)败 FROM T169 tGROUP BY YEAR;方法二:WITH cteAS( SELECT YEAR,CASE RESULT WHEN '胜' THEN 1 WHEN '败'THEN 0 END res FROM T169 ) SELECT YEAR,(SELECT COUNT(res) FROM cte c WHERE res>0 AND t.year =c.year),(SELECT COUNT( res) FROM cte c WHERE res=0 AND t.year =c.year) FROM cte tGROUP BY YEAR;