为此使用动态 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 | 日期 | 数量 | 哈利 | 马克 | 理查德 |
|----|------------|--------|--------|-- ----|----------|
| 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演示