我在MySql中有两个表,
shareholders
id name value
1 harry 20
2 mark 60
3 richard 20
第二个表是
transactions
id date amount
1 2013-11-01 2000
2 2013-11-01 150
3 2013-11-01 300
4 2013-11-02 700
5 2013-11-02 5400
第一个表包含交易金额的百分比。 是否有可能在MySQL中有一个选择查询将返回以下输出?
transid amount harry mark richard ,.....
1 2000 400 1200 400
2 150 30 90 30
3 300 60 180 60
.
.
.
股东人数不固定
答案 0 :(得分:3)
为此使用动态SQL
SET @sql = NULL;
SELECT GROUP_CONCAT(CONCAT(
'MAX(CASE WHEN h.id = ', id,
' THEN amount * ', value / 100,
' END) `', name, '`'))
INTO @sql
FROM shareholders;
SET @sql = CONCAT(
'SELECT t.id transaction_id, t.date, t.amount, ', @sql,
' FROM transactions t CROSS JOIN shareholders h
GROUP BY t.id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
输出:
| TRANSACTION_ID | DATE | AMOUNT | HARRY | MARK | RICHARD | |----------------|------------|--------|-------|------|---------| | 1 | 2013-11-01 | 2000 | 400 | 1200 | 400 | | 2 | 2013-11-01 | 150 | 30 | 90 | 30 | | 3 | 2013-11-01 | 300 | 60 | 180 | 60 | | 4 | 2013-11-02 | 700 | 140 | 420 | 140 | | 5 | 2013-11-02 | 5400 | 1080 | 3240 | 1080 |
这是 SQLFiddle 演示
为了简化调用端的内容,您可以将其包装在存储过程中
DELIMITER $$
CREATE PROCEDURE shareholders_report()
BEGIN
SET @sql = NULL;
SELECT GROUP_CONCAT(CONCAT(
'MAX(CASE WHEN h.id = ', id,
' THEN amount * ', value / 100,
' END) `', name, '`'))
INTO @sql
FROM shareholders;
SET @sql = CONCAT(
'SELECT t.id transaction_id, t.date, t.amount, ', @sql,
' FROM transactions t CROSS JOIN shareholders h
GROUP BY t.id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;
然后使用它:
CALL shareholders_report();
这是 SQLFiddle 演示