sql查询语句,化繁为简——求教高手
小__猪 2003-09-04 04:25:21 有这样一张表table1,有如下三个字段month(月),day(天),value(值),
每天最多有一个值。
month day value
----------- ----------- -----------
1 1 3
1 2 4
1 3 5
1 4 5
1 5 22
2 1 24
2 2 25
2 3 55
2 5 78
3 2 67
3 3 56
3 4 34
希望能用一句sql查询语句,来实现如下结果:
某天 一月 二月 三月
day month1 month2 month3
----------- ----------- ----------- -----------
1 3 24 NULL
2 4 25 67
3 5 55 56
4 5 NULL 34
5 22 78 NULL
我尝试了一下自连接的方法如下:
select distinct m.day,month1=m1.value,month2=m2.value,month3=m3.value from table1 m left join table1 m1 on m1.day=m.day and m1.month=1 left join table1 m2 on m2.day=m.day and m2.month=2 left join table1 m3 on m3.day=m.day and m3.month=3
虽然也可以得到上述结果,但是我觉得太繁了些,特别当是12个月的话,而且查询效率也不高,如果不用distinct将会有好多重复的记录。
不知道哪位大侠能给我一个简洁一些的表达方法。