我很难在MySQL中使用Dynamic Pivots,现在已经为该项目奋斗了5周多。 使用此代码,我可以生成动态数据透视表:
if($period == "YEARWEEK"){
$sql = "
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'SUM(CASE WHEN (".$period."(redeem_pledge)) = ',
(".$period."(redeem_pledge)),
' THEN AMOUNT else 0 END) AS `',
(".$period."(redeem_pledge)),
'`'
)
ORDER BY redeem_pledge ASC ) AS `pivot_columns`
FROM record_pledge
WHERE redeem_pledge BETWEEN ? AND ?
ORDER BY redeem_pledge ASC
";
$stmt = $pdo->prepare($sql);
$date_from = $this->input->get('date_from') ? $this->input->get('date_from') : '2017-05-01';
$date_to = $this->input->get('date_to') ? $this->input->get('date_to') : date('Y-m-d');
$stmt->execute([$date_from, $date_to]);
$row = $stmt->fetch();
$stmt->closeCursor();
$pivot_columns = $row['pivot_columns'];
$sql = "
SELECT title AS `Pledge Purpose`, {$pivot_columns}
from record_pledge t1
join setting_pledge_purpose ON t1.purpose_pledge =
setting_pledge_purpose.id
WHERE t1.`redeem_pledge` BETWEEN ? AND ?
GROUP BY title asc WITH ROLLUP
";
$stmt = $pdo->prepare($sql);
$stmt->execute([$date_from, $date_to]);
$results = $stmt->fetchAll();
$stmt->closeCursor();
通过传递传递给它的参数来切换$ period的值,使用此方法生成月度报告或年度报告没有问题。但是,当我使用YEARWEEK作为函数时,数据将被复制,如下所示:
传递给它的参数:
date_from=2017-06-01
date_to=2017-10-01
period=YEARWEEK
SQL FIDDLE: Here 这是拼图的最后一部分,非常感谢任何帮助!!!!!