如何使用agregate函数而不在oracle中的所有列上使用group by?

时间:2016-10-13 17:24:57

标签: sql oracle oracle11g

例如我有这张桌子X

    Date1  *Date2  *Price  * Brand*Comment  
    ****************************************
    111016 *131016 *100    *a     *h   
    121016 *131016 *200    *a     *i  
    111016 *131016 *300    *b     *j
    121016 *131016 *100    *b     *k

我想在date2 131016的max(date1)中加上(价格),品牌,评论。

    sum(price) *brand *Comment
    **************************
    300        *a     *i
    400        *b     *k

我正在尝试这样的查询

select s1.sum(price),s1.brand,s2.comment
from X s1, X s2
where s1.date2='131016'
    and s1.brand=s2.brand
    and s2.date1=(select max(date1) from X where date2='131016')
group by s1.brand;

看来我的方法在这里是错误的。 我的方法应该是以上述方式显示数据的select查询?请记住,表格中有超过20列与我需要显示总和的价格类似。

2 个答案:

答案 0 :(得分:0)

在这里你可以使用分析函数 SUM(col1)OVER(PARTITION BY col2,...,coln ORDER BY col2,..,coln),如下所示:

select sum(s1.price) over(partition by s1.brand),
       s1.brand, 
       s2.comment
  from X s1, X s2
 where s1.date2 = ‘131016’
   and s1.brand = s2.brand
   and s2.date1 = (select max(date1) from X where date2 = s1.date2); 

虽然我们汇总数据,但GROUP BY是必要的。但是可以通过使用PARTITION BY来避免GROUP BY(而PARTITION类似于GROUP BY)。

查看此链接以更好地了解分析功能。 https://docs.oracle.com/cd/E11882_01/server.112/e41084/functions182.htm#SQLRF06115

答案 1 :(得分:0)

Oracle安装程序

CREATE TABLE X ( Date1, Date2, Price, Brand, "Comment" ) AS
SELECT DATE '2016-10-11', DATE '2016-10-13', 100, 'a', 'h' FROM DUAL UNION ALL   
SELECT DATE '2016-10-12', DATE '2016-10-13', 200, 'a', 'i' FROM DUAL UNION ALL  
SELECT DATE '2016-10-11', DATE '2016-10-13', 300, 'b', 'j' FROM DUAL UNION ALL
SELECT DATE '2016-10-12', DATE '2016-10-13', 100, 'b', 'k' FROM DUAL;

Oracle查询

SELECT SUM( price ) AS total_price,
       brand,
       MAX( "Comment" ) KEEP ( DENSE_RANK LAST ORDER BY date1 ) AS "Comment"
FROM   X
WHERE  Date2 = DATE '2016-10-13'
GROUP BY brand;

<强>输出

TOTAL_PRICE BRAND Comment
----------- ----- -------
        300 a     i       
        400 b     k