查询语句求解,行转列的
A表:
ID 姓名
1 张三
2 李四
B表:
ID 日期 电费 水费
1 2012-03-01 20 30
2 2012-03-02 30 50
1 2012-03-02 40 79
-----------------------------------------
需要查询一个时间段范围2012-03-01到2012-03-02的记录表
结果如下:
ID 姓名 2012-03-01电费 2012-03-01水费 2012-03-02电费 2012-03-02水费
1 张三 20 30 40 79
2 李四 null null 30 50
行的数量由日期范围决定
------解决方案--------------------
http://blog.csdn.net/acmain_chm/article/details/4283943
MySQL交叉表
在某些数据库中有交叉表,但在MySQL中却没有这个功能,但网上看到有不少朋友想找出一个解决方法,特发贴集思广义。http://topic.csdn.net/u/20090530/23/0b782674-4b0b-4cf5-bc1a-e8914aaee5ab.html?96198现整理解法如下:数据样本: create table tx( id int primary key, c1 c.
------解决方案--------------------
select a.id,a.姓名,
sum(if(日期='2010-03-02', 电费,0)) as `2010-03-02电费`,
sum(if(日期='2010-03-02', 水费,0)) as `2010-03-02水费`,
sum(if(日期='2010-03-01', 电费,0)) as `2010-03-01电费`,
sum(if(日期='2010-03-01', 水费,0)) as `2010-03-01水费`
from b inner join a on a.id=b.id
group by a.id,a.姓名
用SP生成类似SQL语句
------解决方案--------------------
示例:
DELIMITER $$
DROP PROCEDURE IF EXISTS rowtocol$$
CREATE PROCEDURE rowtocol(abeg DATE ,aend DATE)
BEGIN
DECLARE asql VARCHAR(1000) DEFAULT '';
WHILE abeg<=aend DO
SET asql=CONCAT(asql,'sum(if(日期=\'',abeg,'\' ,电费,0)) as ', '`',abeg,'电费`,'
'sum(if(日期=\'',abeg,'\' ,水费,0)) as ', '`',abeg,'水费`,');
-- SELECT asql;
SET abeg=DATE_ADD(abeg,INTERVAL 1 DAY);
END WHILE;
SET ASQL=CONCAT('select a.id,a.姓名,',LEFT(ASQL,LENGTH(ASQL)-49),' from b inner join a on a.id=b.id
group by a.id,a.姓名');
SET @ASQL=ASQL;
PREPARE STML FROM @ASQL;
EXECUTE STML;
SELECT asql;
END$$
DELIMITER ;
CALL rowtocol('2011-03-01','2011-3-2');