应该主要是直接查询以获取详细信息,然后您的报告可以根据需要汇总总计。获取与付款相关的原始数据可能类似于
select
p.id,
p.name,
p.address,
p.orderNumber,
p.promoCode,
o.id as OrderID,
o.orderQuantity,
prod.sku,
prod.title,
prod.description,
prod.price
from
payments p
join order o
on p.orderNumber = o.orderNumber
join products prod
on o.productSku = prod.sku
根据评论,尝试在多个列上进行模拟 Pivot - FIXED COLUMNS THOUGH(使用原始查询的别名作为“PQ”(预查询),但具体按订单 ID 排序,因此订单项也在一起。
select
PQ.ID,
PQ.Name,
PQ.address,
PQ.orderNumber,
PQ.promoCode,
max( if( PQ.sku = 'umbrella1212', PQ.Price, 0.00 )) as Umbrella1212Price,
sum( if( PQ.sku = 'umbrella1212', PQ.OrderQuantity, 0.00 )) as Umbrella1212Qty,
max( if( PQ.sku = 'umbrella1010', PQ.Price, 0.00 )) as Umbrella1010Price,
sum( if( PQ.sku = 'umbrella1010', PQ.OrderQuantity, 0.00 )) as umbrella1010Qty,
max( if( PQ.sku = 'rainbootlg', PQ.Price, 0.00 )) as rainbootlgPrice,
sum( if( PQ.sku = 'rainbootlg', PQ.OrderQuantity, 0.00 )) as rainbootlgQty,
max( if( PQ.sku = 'rubFlrmts', PQ.Price, 0.00 )) as rubFlrmtsPrice,
sum( if( PQ.sku = 'rubFlrmts', PQ.OrderQuantity, 0.00 )) as rubFlrmtsQty,
sum( PQ.Price * PQ.OrderQuantity ) as OrderTotal
from
( select
p.id,
p.name,
p.address,
p.orderNumber,
p.promoCode,
o.id as OrderID,
o.orderQuantity,
prod.sku,
prod.title,
prod.description,
prod.price
from
payments p
join order o
on p.orderNumber = o.orderNumber
join products prod
on o.productSku = prod.sku
order by
p.id,
o.id ) PQ
group by
PQ.ID,
PQ.Name,
PQ.address,
PQ.orderNumber,
PQ.promoCode
由于名称/地址/订单#/促销代码对于所有关联的订单项都是相同的,具有相同的“订单号”,因此它们出现在分组依据中。否则 MySQL 可能会抱怨列不是聚合函数的一部分(sum、min、max、avg 等)