Oracle:如何总结 Oracle 中的别名列
Oracle: How to sum up alias column in Oracle
我有一个问题:
SELECT od.*, i.name AS item_name, (od.quantity*od.price) AS sub_total
FROM order_details od
JOIN items i ON od.item_id = i.item_id
WHERE order_id = 9
它产生以下结果。
现在,我想总结 SUB_TOTAL
列,我希望结果为 1300
。
我尝试了以下代码,但它不起作用。
SELECT od.*, i.name AS item_name, (od.quantity*od.price) AS sub_total, SUM(sub_total) AS total
FROM order_details od
JOIN items i ON od.item_id = i.item_id
WHERE order_id = 9
请帮忙
那是 window SUM()
- 你不能重复使用列别名,你需要重复表达式,或者使用子查询或 CTE:
SELECT od.*, i.name AS item_name, (od.quantity * od.price) AS sub_total,
SUM(od.quantity * od.price) OVER() AS total
FROM order_details od
JOIN items i ON od.item_id = i.item_id
WHERE order_id = 9
您可能需要根据您的实际需要调整 window SUM()
的 OVER()
子句。上面的查询将在两行上显示 1300
。您可以使用 PARTITION BY
子句将行集分成组,and/or 使用 ORDER BY
计算 运行 总和。
使用window函数:
SELECT od.*, i.name AS item_name, (od.quantity*od.price) AS sub_total,
SUM((od.quantity*od.price) OVER (ORDER BY order_detail_id)
FROM order_details od JOIn
items i
ON od.item_id = i.item_id
WHERE order_id = 9;
请注意,您不能重复使用别名;你需要重新计算。
我有一个问题:
SELECT od.*, i.name AS item_name, (od.quantity*od.price) AS sub_total
FROM order_details od
JOIN items i ON od.item_id = i.item_id
WHERE order_id = 9
它产生以下结果。
现在,我想总结 SUB_TOTAL
列,我希望结果为 1300
。
我尝试了以下代码,但它不起作用。
SELECT od.*, i.name AS item_name, (od.quantity*od.price) AS sub_total, SUM(sub_total) AS total
FROM order_details od
JOIN items i ON od.item_id = i.item_id
WHERE order_id = 9
请帮忙
那是 window SUM()
- 你不能重复使用列别名,你需要重复表达式,或者使用子查询或 CTE:
SELECT od.*, i.name AS item_name, (od.quantity * od.price) AS sub_total,
SUM(od.quantity * od.price) OVER() AS total
FROM order_details od
JOIN items i ON od.item_id = i.item_id
WHERE order_id = 9
您可能需要根据您的实际需要调整 window SUM()
的 OVER()
子句。上面的查询将在两行上显示 1300
。您可以使用 PARTITION BY
子句将行集分成组,and/or 使用 ORDER BY
计算 运行 总和。
使用window函数:
SELECT od.*, i.name AS item_name, (od.quantity*od.price) AS sub_total,
SUM((od.quantity*od.price) OVER (ORDER BY order_detail_id)
FROM order_details od JOIn
items i
ON od.item_id = i.item_id
WHERE order_id = 9;
请注意,您不能重复使用别名;你需要重新计算。