mysql查询统计聚合函数

业务中用户统计报表使用,查询字段使用聚合函数+条件,快速实现报表统计。

SELECT
	MIN( s.org_name ) AS orgName,
	s.way_name AS wayName,
	COUNT( s.id ) AS waybillTotal,
	SUM( s.take_weight ) AS takeWeightTotal,
	SUM( s.revert_weight ) AS revertWeightTotal,
	SUM( s.settlement_num ) AS settleNumTotal,
	ROUND( AVG( s.settlement_num ), 2 ) AS averageLoad,
	SUM( s.final_amount + s.prepay_fee ) AS shipperPayTotal,
	SUM(
		s.prepay_fee +
	IF
	( s.payment_status = 1, s.final_amount, 0 )) AS shipperHasPayTotal,
	COUNT(
	IF
	( s.print_ticket_status = 1, 1, NULL )) AS hasTicketWaybillNum,
	SUM(
	IF
	( s.print_ticket_status = 1, s.prepay_fee + s.final_amount, 0 )) AS hasTicketAmount,
	SUM(
	IF
	( s.print_ticket_status = 1, s.settlement_num, 0 )) AS hasTicketTotalGood,
	COUNT(
	IF
	( s.print_ticket_status != 1, 1, NULL )) AS waitPrintWaybillNum,
	SUM(
	IF
	( s.print_ticket_status != 1, s.prepay_fee + s.final_amount, 0 )) AS waitPrintTicketAmount,
	SUM(
	IF
	( s.print_ticket_status != 1, s.settlement_num, 0 )) AS waitPrintTotalGood,
	COUNT(
	IF
	( s.print_ticket_status = 1 AND s.payment_status = 1, 1, NULL )) AS hasTicketAndPayWaybillNum,
	SUM(
	IF
	( s.print_ticket_status = 1 AND s.payment_status = 1, s.prepay_fee + s.final_amount, 0 )) AS hasTicketAndPayAmount,
	SUM(
	IF
	( s.print_ticket_status = 1 AND s.payment_status = 1, s.settlement_num, 0 )) AS hasTicketAndPayTotalGood,
	COUNT(
	IF
	( s.print_ticket_status = 1 AND s.payment_status = 0, 1, NULL )) AS hasTicketAndUnPayWaybillNum,
	SUM(
	IF
	( s.print_ticket_status = 1 AND s.payment_status = 0, s.prepay_fee + s.final_amount, 0 )) AS hasTicketAndUnPayAmount,
	SUM(
	IF
	( s.print_ticket_status = 1 AND s.payment_status = 0, s.settlement_num, 0 )) AS hasTicketAndUnPayTotalGood,
	SUM(
		d.final_amount + d.carrier_fee +
	IF
	( d.prepay_style = 2, d.prepay_fee, 0 )) AS driverPayTotal,
	SUM(
		d.settle_oil_fee +
	IF
	( d.prepay_style = 1, d.prepay_fee, 0 )) AS fuelFeeTotal,
	SUM(
	IF
		( d.prepay_style = 2, d.prepay_fee, 0 ) +
	IF
	( d.payment_status = 1, d.final_amount + d.carrier_fee, 0 )) AS driverHasPayTotal,
	SUM(
	IF
		(
			d.payment_status = 1 
			AND (
				s.payment_status = 0 
			OR s.payment_time >= DATE_FORMAT( ?, '%Y-%m-%d' )),
		IF
			( d.prepay_style = 2, d.prepay_fee, 0 ) + d.final_amount + d.carrier_fee,
			0 
		)) AS advanceAmount 
FROM
	settlement_shipper_bill s
	LEFT JOIN settlement_driver_bill d ON s.waybill_no = d.waybill_no 
WHERE
	s.platform_id = ? 
	AND DATE_FORMAT( s.take_time, '%Y-%m-%d' ) >= DATE_FORMAT(?, '%Y-%m-%d' ) 
	AND DATE_FORMAT( s.take_time, '%Y-%m-%d' ) <= DATE_FORMAT(?, '%Y-%m-%d' ) AND INSTR(?, s.org_name ) > 0 
GROUP BY
	s.way_name

你可能感兴趣的:(mysql,数据库)