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

如何在SQL查询中添加小计列(订购数量×标准价格)

给SQL查询添加小计列的方法

嘿,这事儿超简单!你只需要在SELECT子句里新增一个计算字段,直接用standard_price乘以ordered_quantity就行,还能给这个列起个清晰的别名,比如subtotal(小计)。

基础修改后的查询语句

SELECT 
  product_description, 
  ordered_quantity, 
  standard_price,
  standard_price * ordered_quantity AS subtotal
from m_order_line 
join m_product using (product_id) 
where order_id = 1006;

可选:格式化小计金额(保留两位小数)

如果希望小计金额显示为标准的货币格式(比如保留两位小数),可以根据你使用的数据库添加格式化函数,举几个常见例子:

  • MySQL/PostgreSQL:用ROUND()函数
    SELECT 
      product_description, 
      ordered_quantity, 
      standard_price,
      ROUND(standard_price * ordered_quantity, 2) AS subtotal
    from m_order_line 
    join m_product using (product_id) 
    where order_id = 1006;
    
  • Oracle:同样可以用ROUND(),或者TO_CHAR()格式化
    SELECT 
      product_description, 
      ordered_quantity, 
      standard_price,
      ROUND(standard_price * ordered_quantity, 2) AS subtotal
    from m_order_line 
    join m_product using (product_id) 
    where order_id = 1006;
    

这样执行查询后,结果里就会多出一列subtotal,显示每一行产品的订购金额小计啦~

内容的提问来源于stack exchange,提问作者Kira

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 12:37:33