表结构如下:
create table date(day varchar(100) not null); create table register(registerCount bigint not null); create table login(loginCount bigint not null);
原sql如下:select day,registerCount,loginCount
from( select day from date where day between 20120101 and 20120103)tmp left join( select registerCount from register)r on tmp.day=r.day left join( select loginCount from login)l on tmp.day=l.day group by day;
原结果集如下:
想更改为如下结果:
水平有限,请高手搭救,要详细sql
你这条sql 貌似还有问题吧 ,先参考这个 看看
[code="java"]表名:table
字段:user , id , score
数据如下:
+----------+----------+----------------+
| user | id | score |
| u1 | 1 | 1.2 |
| u1 | 2 | 2.3 |
| u1 | 3 | 2.5 |
| u2 | 1 | 3.4 |
| u2 | 2 | 4.5 |
| u2 | 3 | 2.6 |
+----------+----------+----------------+
需要得到如下的查询结果:
+----------+----------------------+----------------------+----------------------+
| user | id_1_score | id_2_score | id_3_score |
| u1 | 1.2 | 2.3 | 2.5 |
| u2 | 3.4 | 4.5 | 2.6 |
+----------+----------------------+----------------------+----------------------+
SQL语句:
Select user,
sum(if(id=1, score,0)) as id_1_score,
sum(if(id=2, score,0)) as id_2_score,
sum(if(id=3, score,0)) as id_3_score
from table
group by user;[/code]
需要在程序中拼,
如
3、行列转换
[姓名] [学科] [成绩]
张三 语文 80
张三 数学 90
李四 语文 85
李四 数学 92
select s.snum,s.sname,c.cname,sum(g.score)
from tbl_student s, tbl_course c, tbl_grade g
where s.snum = g.snum and c.cnum=g.cnum
group by s.snum, s.sname,c.cname
select sname,
(select score from tbl_grade g, tbl_course c where c.cname='语文' and g.snum = s.snum and g.cnum = c.cnum) 语文,
(select score from tbl_grade g, tbl_course c where c.cname='数学' and g.snum = s.snum and g.cnum = c.cnum)数学
from tbl_student s;
即需求是 列名是你的字段名 在程序里拼好字段 再进行查
http://hdxiong.iteye.com/blog/836956
这是一个常见的行转列的例子,很直观,使用mysql的函数
case when then else end 楼主可以看一下。
个人觉得 你的那个行列转换似乎有些问题啊 你的第一列怎么显示啊 用sql能这样匹配两列吗?没得结论,楼主解决的话,晾一下。
数据转置的问题,用Oracle的pivot关键字实现起来比较方便,但Mysql等其他数据库没有提供,硬拼的写法不容易理解和维护,也难以实现动态列的效果。这种结果集看起来象是为报表服务的,可以采用集算器来做,代码易懂。
A1=query(“select day,registerCount,loginCount from(…)”) //你的那句SQL
data=create(类别).record(["registerCount","loginCount"]) //只有一个字段的新表data
A3=for A1 //循环A1中的记录
B4=B3. registerCount & B3. loginCount //将当前记录的字段进行纵向拼接
B5= data=eval("data.derive(B4(#):"+ string(A3.day) +")") //给A2增加一个新字段。
集算器是结构化数据计算工具,可以通过JDBC与JAVA集成,可参考http://blog.sina.com.cn/s/blog_e4de31d00102v6gw.html