将输出合并为一个

时间:2016-05-28 05:48:02

标签: sql oracle

    Select Category, Books.ISBN,
Orderitems.Quantity * (Books.Retail - Books.Cost) AS Category_Profit
From BOoks
INNER JOIN Orderitems
ON BOOKS.ISBN=ORDERITEMS.ISBN

示例输出:

Category            ISBN           Category_Profit
Family life         1234                 50
Family Life         1234                 50
Family Life         1234                 100
Fitness             4321                 10
Fitness             4321                 20

等等,等等,

如何使输出将每个类别的所有值计算为一行?

Family Life        1234     200
Fitness            4321     30

3 个答案:

答案 0 :(得分:1)

因为您已将此作为起点,所以请准确使用您拥有的临时表,并从中提取数据:

Select Category, ISBN, Sum(Category_Profit) From
(
select Category, Books.ISBN as ISBN,
Orderitems.Quantity * (Books.Retail - Books.Cost) AS Category_Profit
From Books
INNER JOIN Orderitems
ON BOOKS.ISBN=ORDERITEMS.ISBN
) temp
group by Category, ISBN

您很好地组织了数据,因此很容易在Profit上实现总和。您按类别和ISBN进行分组,以获得具有相应利润的所有这些列的唯一对。

如果您不想使用子查询,您可以在查询中求和(但我觉得在更改之前将现有查询用作子查询是有帮助的,只是为了确保它有效:

select Category, Books.ISBN,
SUM(Orderitems.Quantity * (Books.Retail - Books.Cost)) AS Category_Profit
From Books
INNER JOIN Orderitems
ON BOOKS.ISBN=ORDERITEMS.ISBN
 temp
group by Category, Books.ISBN

答案 1 :(得分:1)

分组可以用来解决您的问题。

注意:在Group by子句中,可以根据某些列对一组表行进行分组,在select子句中,可以按列或按其他列的聚合函数(SUM,MIN,MAX,Count等)进行分组。所示。

参考: http://www.dofactory.com/sql/group-by

使用group by,如下所示。希望这能解决问题。

 Select Category, Books.ISBN,
 SUM(Orderitems.Quantity * (Books.Retail - Books.Cost)) AS Category_Profit
 From BOoks
 INNER JOIN Orderitems
 ON BOOKS.ISBN=ORDERITEMS.ISBN
 Group by Category,ISBN 

答案 2 :(得分:0)

使用GROUP_BY& SUM,语法:

SELECT column_name, SUM(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;

参考:SQL GROUP_BY

在你的桌子上你可以跑:

Select Category, ISBN, Sum(Category_Profit) From Table1
group by Category, ISBN;

表1:

Category            ISBN           Category_Profit
Family life         1234                 50
Family Life         1234                 50
Family Life         1234                 100
Fitness             4321                 10
Fitness             4321                 20

输出:

|    Category | ISBN | Sum(Category_Profit) |
|-------------|------|----------------------|
| Family life | 1234 |                  200 |
|     Fitness | 4321 |                   30 |

Fiddle