合并一列的值并汇总第二列

时间:2016-06-05 16:29:59

标签: sql database oracle oracle-sqldeveloper

我是Oracle SQL的新手。我正在尝试对大约三个表执行操作。基本上,我有三个表:艺术家,交易,工作。我正在努力找回拥有最多艺术品的艺术家。当我运行查询时,我得到重复的值,我不完全确定如何合并列。

这是我最初执行的查询

SELECT FIRSTNAME || '' || LASTNAME AS ARTISTNAME, TITLE, SALESPRICE
FROM DTOOHEY.ARTIST A, DTOOHEY.WORK W, DTOOHEY.TRANS T
WHERE A.ARTISTID = W.ARTISTID
AND W.WORKID = T.WORKID
AND DATESOLD IS NOT NULL;

Here is the result. 我想要实现的是合并艺术家姓名,然后总结他们的销售价格。例如,对于艺术家Joan Miro,我希望它只显示一个值为“Joan Miro”,而销售价格是合并行的总和(400 + 200 = 600)。像

这样的东西
Artist Name | SalesPrice    

Joan Miro   | 600

这样的事情可能吗?我不完全确定如何使用MERGE函数,我不确定这是否是我需要在这里使用的。

编辑:

抱歉,我忘了提到我确实使用过GROUP BY。我也试过这个问题:

SELECT FIRSTNAME || '' || LASTNAME AS ARTISTNAME, TITLE, SUM(SALESPRICE)
FROM DTOOHEY.ARTIST A, DTOOHEY.WORK W, DTOOHEY.TRANS T
WHERE A.ARTISTID = W.ARTISTID
AND W.WORKID = T.WORKID
AND DATESOLD IS NOT NULL
GROUP BY FIRSTNAME, LASTNAME;

我收到错误说:

ORA-00979: not a GROUP BY expression
00979. 00000 -  "not a GROUP BY expression"
*Cause:    
*Action:
Error at Line: 42 Column: 51

2 个答案:

答案 0 :(得分:0)

您需要使用GROUP BYSUM

另外,为清楚起见,我建议使用ANSI连接语法。

SELECT FIRSTNAME || '' || LASTNAME AS ARTISTNAME, SUM(SALESPRICE) AS TOTAL_SALESPRICE
FROM DTOOHEY.ARTIST A
JOIN DTOOHEY.WORK W ON A.ARTISTID = W.ARTISTID
JOIN DTOOHEY.TRANS T ON W.WORKID = T.WORKID
WHERE DATESOLD IS NOT NULL
GROUP BY FIRSTNAME, LASTNAME;

答案 1 :(得分:0)

这正是group by子句的用途。它允许您指定哪些列应该定义一组行(在您的情况下 - 艺术家的名字和姓))并使您在其他列上应用一些聚合函数(在您的情况下为 - sum)。即:

SELECT   FIRSTNAME || '' || LASTNAME AS ARTISTNAME, SUM(SALESPRICE)
FROM     DTOOHEY.ARTIST A, DTOOHEY.WORK W, DTOOHEY.TRANS T
WHERE    A.ARTISTID = W.ARTISTID AND
         W.WORKID = T.WORKID AND
         DATESOLD IS NOT NULL
GROUP BY FIRSTNAME, LASTNAME;

一般评论:
隐式连接(在from子句中有多个表)被认为已被弃用,并且现在已经被忽视了多年。您应该使用显式连接子句:

SELECT   FIRSTNAME || '' || LASTNAME AS ARTISTNAME, SUM(SALESPRICE)
FROM     DTOOHEY.ARTIST A
JOIN     DTOOHEY.WORK W ON A.ARTISTID = W.ARTISTID
JOIN     DTOOHEY.TRANS T ON W.WORKID = T.WORKID
WHERE    DATESOLD IS NOT NULL
GROUP BY FIRSTNAME, LASTNAME;