You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MySQL内连接查询近7天热销商品问题排查与需求实现

解决你的SQL统计问题

Hey there! Let's work through this SQL problem step by step. First, the issue you suspected with the inner join likely stems from incorrect date filtering or improper aggregation of quantity and unit price. Let's fix that while meeting all your requirements:

完整SQL查询语句

SELECT
    p.product_id,
    p.product_name,
    p.brand,
    SUM(ii.quantity * ii.unit_price) AS total_revenue,
    p.current_stock,
    ROUND(((ii.unit_price - p.cost_price) / ii.unit_price) * 100, 2) AS profit_margin_percent
FROM
    orders o
INNER JOIN items_in_order ii ON o.order_id = ii.order_id
INNER JOIN products p ON ii.product_id = p.product_id
INNER JOIN regions r ON o.region_id = r.region_id
WHERE
    r.region_name = '中国'
    AND p.brand = '任天堂'
    AND o.order_date >= DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY)
GROUP BY
    p.product_id, p.product_name, p.brand, p.current_stock, ii.unit_price, p.cost_price
ORDER BY
    total_revenue DESC;

关键细节说明

1. 修复内连接与营收计算问题

  • 精准日期筛选:用DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY)确保只统计近7天的订单(如果用PostgreSQL,替换为CURRENT_DATE - INTERVAL '7 days'即可),避免日期范围错误导致的营收偏差。
  • 正确营收聚合:通过SUM(ii.quantity * ii.unit_price)按商品维度求和,确保每个订单中同商品的数量与单价乘积被正确累加,这应该能让你得到3ds预期的300营收结果。

2. 满足所有需求

  • 中国区任天堂商品营收排行:通过WHERE子句锁定区域和品牌,最后用ORDER BY total_revenue DESC实现从高到低的排行。
  • 当前库存数量:直接从products表的current_stock字段获取,注意在GROUP BY中包含该字段以适配数据库的严格聚合规则。
  • 利润率计算:采用((售价 - 成本价)/售价)*100的标准公式,用ROUND()保留两位小数,直观展示百分比形式的利润率。

灵活调整提示

如果你的表结构有差异(比如单价存在于products表而非items_in_order),只需把ii.unit_price替换为p.sell_price即可;如果需要排除取消/退款订单,可在WHERE中添加o.order_status = '已完成'这类筛选条件。

内容的提问来源于stack exchange,提问作者D. Joe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:58:26