我正在使用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


但这会在最后一行显示收货人和收货人的值。我想要的是仅在最后一行显示所有“ PREPAID”和“ COLLECT”交易的GrandTotal。希望您能提供帮助。

提前致谢!!!

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

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 | B |

1216416 | C | D |

1216417 | E | F |

发生的是:

运单收货人|发货人|

1216415 | E | F |

1216416 | E | F |

1216417 | E | F |

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

最佳答案

如果我理解正确,请使用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;

10-06 06:17