主要原理是利用decode函数、聚集函数(sum/max/min/avg),结合group by分组实现的,具体sql如下:
select t.user_name as 姓名,
MAX(decode(t.course,'语文',score,null)) as 语文,
MAX(decode(t.course,'数学',score,null)) as 数学,
MAX(decode(t.course,'英语',score,null)) as 英语
from RowToCol t group by t.user_name order by t.user_name
*当要分组的值,如例子中的score列是数值型,则聚集函数可以使用sum/max/min/avg,但是字符行的只能使用max/min。
decode函数:
它是一种特有的函数计算方式,相当于计算机语言中的if...else...
decode(条件,值1,翻译值1,值2,翻译值2,...值n,翻译值n,缺省值)
我介几写的:
StringBuffer sb = new StringBuffer();
sb.append("select t.group_line_id,");
sb.append("max(decode (t.rzl_id,'"+rzlidList.get(0).get("RZL_ID").toString()+"',data_content,null)) as rq,");
sb.append("max(decode (t.rzl_id,'"+rzlidList.get(1).get("RZL_ID").toString()+"',data_content,null)) as hj1,");
sb.append("max(decode (t.rzl_id,'"+rzlidList.get(2).get("RZL_ID").toString()+"',data_content,null)) as hj2,");
sb.append("max(decode (t.rzl_id,'"+rzlidList.get(3).get("RZL_ID").toString()+"',data_content,null)) as hx,");
sb.append("max(decode (t.rzl_id,'"+rzlidList.get(4).get("RZL_ID").toString()+"',data_content,null)) as sb,");
sb.append("max(decode (t.rzl_id,'"+rzlidList.get(5).get("RZL_ID").toString()+"',data_content,null)) as lh,");
sb.append("max(decode (t.rzl_id,'"+rzlidList.get(6).get("RZL_ID").toString()+"',data_content,null)) as lx,");
sb.append("max(decode (t.rzl_id,'"+rzlidList.get(7).get("RZL_ID").toString()+"',data_content,null)) as qccm,");
sb.append("max(decode (t.rzl_id,'"+rzlidList.get(8).get("RZL_ID").toString()+"',data_content,null)) as qclm,");
sb.append("max(decode (t.rzl_id,'"+rzlidList.get(9).get("RZL_ID").toString()+"',data_content,null)) as qccr");
sb.append(" from r5_yxrz_data t");
sb.append(" where re_id = ? and rz_id = ?");
sb.append(" group by t.group_line_id");
sb.append(" order by t.group_line_id");