简体   繁体   English

Oracle:如何总结 Oracle 中的别名列

[英]Oracle: How to sum up alias column in Oracle

I have a query:我有一个疑问:

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

It produces the following result.它产生以下结果。 在此处输入图片说明

Now, I want to sum up SUB_TOTAL column and I want the result as 1300 .现在,我想总结SUB_TOTAL列,我希望结果为1300

I've tried the following code but it doesn't work.我已经尝试了以下代码,但它不起作用。

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

Please help.请帮忙。

That's a window SUM() - and you can't reuse the column alias, you need to repeat the expression, or use a subquery or CTE:这是一个窗口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

You might need to adjust the OVER() clause of the window SUM() according to your actual requirement.您可能需要根据您的实际需求调整窗口SUM()OVER()子句。 The above query will bring 1300 on both rows.上面的查询将在两行上带来1300 You can use a PARTITION BY clause to divide the set of rows into groups, and/or use ORDER BY to compute a running sum.您可以使用PARTITION BY子句将行集划分为组,和/或使用ORDER BY计算运行总和。

Use window functions:使用窗口函数:

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;

Note that you cannot re-use the alias;请注意,您不能重复使用别名; you need to repeat the calculation.您需要重复计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM