如何在以下方案中使用Oracle Group BY

时间:2012-10-03 09:46:14

标签: sql oracle group-by

以下是一个非常基本的场景。

我发现即使经过大量的例子,我也很难理解GROUP BY的工作原理。

在下面的场景中,我需要获得最小的日期值,并需要将我的查询1转换为查询2.

QUERY1:

SELECT b.aper07_req_created_s,
       b.aper06_req_status_k,
       a.aper06_req_status_x
FROM   iaper07_employee_offbrd_req b,
       iaper06_req_status a
WHERE  a.aper06_req_status_k = b.aper06_req_status_k
       AND b.aper07_req_k = 3387
       AND b.aper06_req_status_k = 4
ORDER  BY b.aper07_req_created_s 

查询2:

SELECT Min(b.aper07_req_created_s),
       b.aper06_req_status_k,
       a.aper06_req_status_x
FROM   iaper07_employee_offbrd_req b,
       iaper06_req_status a
WHERE  a.aper06_req_status_k = b.aper06_req_status_k
       AND b.aper07_req_k = 3387
       AND b.aper06_req_status_k = 4
GROUP  BY b.aper06_req_status_k,
          a.aper06_req_status_x
ORDER  BY b.aper07_req_created_s 

查询2未能说明它不是按表达式分组。

任何人都可以通过一些解释帮助我了解如何获得第二次查询吗?

3 个答案:

答案 0 :(得分:2)

在查询2中,ORDER BY子句无效。

GROUP BY之后(因此,在HAVINGORDER BYSELECT部分中),表达式必须基于GROUP-BY列,基于常量,或其他列的聚合函数。

您可以改为使用ORDER BY MIN(b.aper07_req_created_s)

答案 1 :(得分:1)

您的问题可能是ORDER BY b.aper07_req_created_s,请尝试将其替换为:

ORDER BY Min(b.aper07_req_created_s):

  SELECT Min(b.aper07_req_created_s),
           b.aper06_req_status_k,
           a.aper06_req_status_x
    FROM   iaper07_employee_offbrd_req b,
           iaper06_req_status a
    WHERE  a.aper06_req_status_k = b.aper06_req_status_k
           AND b.aper07_req_k = 3387
           AND b.aper06_req_status_k = 4
    GROUP  BY b.aper06_req_status_k,
              a.aper06_req_status_x
    ORDER  BY Min(b.aper07_req_created_s)

ORDER BY 1:

 SELECT Min(b.aper07_req_created_s),
           b.aper06_req_status_k,
           a.aper06_req_status_x
    FROM   iaper07_employee_offbrd_req b,
           iaper06_req_status a
    WHERE  a.aper06_req_status_k = b.aper06_req_status_k
           AND b.aper07_req_k = 3387
           AND b.aper06_req_status_k = 4
    GROUP  BY b.aper06_req_status_k,
              a.aper06_req_status_x
    ORDER  BY 1

您还可以使用别名:

    SELECT Min(b.aper07_req_created_s) minemp,
           b.aper06_req_status_k,
           a.aper06_req_status_x
    FROM   iaper07_employee_offbrd_req b,
           iaper06_req_status a
    WHERE  a.aper06_req_status_k = b.aper06_req_status_k
           AND b.aper07_req_k = 3387
           AND b.aper06_req_status_k = 4
    GROUP  BY b.aper06_req_status_k,
              a.aper06_req_status_x
    ORDER  BY minemp

Here你可以找到更多信息。

答案 2 :(得分:1)

尝试解释GROUP BY在SQL中的工作原理:
(我会说)它的工作原理与您期望它的工作原理完全相同 如果你有一篮水果,你想要通过分组类型得到你所拥有的所有水果的数量:

SELECT groupingType, count(groupingType)
FROM fruitBasket
GROUP BY groupingType

如果您使用水果类型(苹果,梨......)作为groupingType,那么您将无法在结果中获得水果颜色,因为它们(苹果,梨......)可能具有不同的颜色。以同样的方式,如果你按颜色分组,你将无法获得水果类型...