如何在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
相关产品推荐
相关产品推荐

