带有附加列的SQL数据透视表

时间:2015-01-14 11:44:07

标签: php mysql codeigniter pivot-table

我正在为一家小型快递公司使用Codeigniter和Mysql建立一个快递系统。我想要做的是建立一个数据透视表,显示每种运单(包括总计)的特定付款类型的总付款。

我现在有这个查询:

SELECT IFNULL( p.waybill_number,  'GrandTotal' ) AS Waybill, w.consignee, w.consignor,
       SUM( IF(       p.payment_terms =  'prepaid', p.amount, NULL ) ) AS Prepaid,
       SUM( IF( p.payment_terms =  'collect', p.amount, NULL ) ) AS Collect
FROM payment p JOIN
     waybill w
     ON p.waybill_number = w.waybill_number
GROUP BY p.waybill_number WITH ROLLUP

但是这显示了最后一行中收货人和收货人的价值。我想要的只是显示所有人的GrandTotal" PREPAID"和"收集"最后一行的交易。我希望你能提供帮助。

提前致谢!!!

UPDATE ::: 我已经编辑了我的查询,现在看起来像这样......

SELECT
IFNULL(mw.waybill_number, 'GrandTotal') as Waybill,
CASE WHEN mw.waybill_number THEN c1.name ELSE NULL END as Consignee,
CASE WHEN mw.waybill_number THEN c2.name ELSE NULL END as Consignee,
SUM(IF(p.payment_terms = 'prepaid', p.amount, NULL)) as Prepaid,
SUM(IF(p.payment_terms = 'collect', p.amount, NULL)) as Collect
FROM manifest_waybill mw
JOIN waybill w
on w.waybill_number = mw.waybill_number
LEFT JOIN payment p
on p.waybill_number = mw.waybill_number
JOIN customer c1
on c1.customer_id = w.consignee
JOIN customer c2
on c2.customer_id = w.consignor
WHERE manifest_number = 103
GROUP BY mw.waybill_number WITH ROLLUP

查询运行但结果不是我所期望的。此查询会在每一行中重复收货人和发货人的价值。

我希望结果如下:

运单#|收货人|发货人|

1216415 | A |乙|

1216416 | C | d |

1216417 | E | F |

会发生什么:

运单#|收货人|发货人|

1216415 | E | F |

1216416 | E | F |

1216417 | E | F |

最后一行(121617)的值在每一行中重复

1 个答案:

答案 0 :(得分:0)

如果我理解正确,只需使用case声明:

SELECT IFNULL(p.waybill_number,  'GrandTotal' ) AS Waybill,
       (CASE WHEN p.waybill_number IS NOT NULL THEN w.consignee END) as consignee,
       (CASE WHEN p.waybill_number IS NOT NULL THEN w.consignor END) as consignor,
       SUM(IF(p.payment_terms =  'prepaid', p.amount, NULL ) ) AS Prepaid,
       SUM(IF( p.payment_terms =  'collect', p.amount, NULL ) ) AS Collect
FROM payment p JOIN
     waybill w
     ON p.waybill_number = w.waybill_number
GROUP BY p.waybill_number WITH ROLLUP;