分组和汇总功能存在问题

时间:2020-07-20 00:26:53

标签: sql oracle

在此示例中,我注意到当我简单地使用它时:

select 
    se.name
from trade t
    JOIN stock_exchange se
        on se.stock_ex_id = t.stock_ex_id
    JOIN stock_listing sl
        ON sl.stock_ex_id = se.stock_ex_id
group by se.name;

它将返回我需要的行。但是我需要在select语句中添加更多列。

赞:

SELECT 
    se.name AS "stock exchange name",
      se.stock_ex_id AS "stock exchange ID",
      sl.stock_symbol AS "stock symbol",
      SUM(t.shares) AS "highest total trade volumn"
    FROM trade t
        join stock_exchange se
            on se.stock_ex_id = t.stock_ex_id
        join stock_listing sl
            on sl.stock_ex_id = se.stock_ex_id and sl.stock_id = t.stock_id
    WHERE t.stock_ex_id is not null
    GROUP BY se.name,se.stock_ex_id, sl.stock_symbol
    HAVING SUM(t.shares) =(
        SELECT 
            MAX(SUM(t.shares))
        FROM(
            SELECT 
                SUM(shares)
            FROM trade tr
            WHERE tr.stock_ex_id is not null
            GROUP BY tr.trade_id
        )
    )
    ORDER BY se.name, sl.stock_symbol;

我测试了几次,当我在第一个group by子句中添加se.stock_ex_id,sl.stock_symbol时出现了问题。输出将包含另外3行,而不是其组的最大值。那么我该如何解决呢?

1 个答案:

答案 0 :(得分:0)

使用Windows函数并将其放在子查询中。下面的查询未经测试,因此只是一个框架:

Select * from 
(Select t.*, max(highest) OVER (PARTITION BY tr.trade_id) max_sal from 
(SELECT 
    se.name AS "stock exchange name",
      se.stock_ex_id AS "stock exchange ID",
      sl.stock_symbol AS "stock symbol",
      SUM(t.shares) OVER (PARTITION BY se.name) AS "highest "
    FROM trade t
        join stock_exchange se
            on se.stock_ex_id = t.stock_ex_id
        join stock_listing sl
            on sl.stock_ex_id = se.stock_ex_id and sl.stock_id = t.stock_id
 WHERE t.stock_ex_id is not null) 
 WHERE tr.stock_ex_id is not null) highest = max_Sal;

另一种可能是:

Select * from (SELECT 
        se.name AS "stock exchange name",
          se.stock_ex_id AS "stock exchange ID",
          sl.stock_symbol AS "stock symbol",
          SUM(t.shares) OVER (PARTITION BY se.name) AS "highest "
        FROM trade t
            join stock_exchange se
                on se.stock_ex_id = t.stock_ex_id
            join stock_listing sl
                on sl.stock_ex_id = se.stock_ex_id and sl.stock_id = t.stock_id
     WHERE t.stock_ex_id is not null)
WHERE highest = (SELECT 
            MAX(SUM(t.shares))
        FROM(
            SELECT 
                SUM(shares)
            FROM trade tr
            WHERE tr.stock_ex_id is not null
            GROUP BY tr.trade_id))
order 1,3

如果您正在寻找额外的乐趣,也可以尝试使用this