1

我已经找到了解决方案,但是如果其中一个列是子查询,我如何将它包含在 group by 中,或者我是否需要将其包含在 group by 中。我将在此处粘贴查询..

SELECT s.customerid, s.denomid,
       (SELECT su.quantity
         FROM   stockupdations su
         WHERE  s.customerid = su.custid
         AND    s.denomid = su.denomid
         AND    s.curid = su.curid) AS cur_stock, c.name AS cus_name, d.denomname AS denom,
       cur.curcode AS currency
FROM   stock s
LEFT   JOIN customers c
ON     s.customerid = c.custid
LEFT   JOIN denomination d
ON     d.denomid = s.denomid
LEFT   JOIN currency cur
ON     cur.curid = s.curid
GROUP  BY s.denomid, s.customerid, c.name, d.denomname, cur.curcode
ORDER  BY s.customerid ASC
4

3 回答 3

0

你不必一次做所有事情。尝试将您的查询分成多个部分。子查询、分析函数或其他复杂的逻辑对于外部查询看起来就像简单的行。(不用担心性能,Oracle 会重写它,如果有意义的话,一切都会一步到位。)

--Step 3
select [simple values]
from
(
  --Step 2
  select [insanity]
  from
  (
    --Step 1
    select [madness]
    from
    [impossible joins]
  )
)
group by [simple values]
于 2010-10-14T03:33:27.987 回答
0

WITH 语句呢?

WITH tmp AS
(
    SELECT s.customerid, s.denomid,
           c.name AS cus_name,
           d.denomname AS denom,
           cur.curcode AS currency
    FROM   stock s
    LEFT   JOIN customers c
    ON     s.customerid = c.custid
    LEFT   JOIN denomination d
    ON     d.denomid = s.denomid
    LEFT   JOIN currency cur
    ON     cur.curid = s.curid
    GROUP  BY s.denomid, s.customerid, c.name, d.denomname, cur.curcode
    ORDER  BY s.customerid ASC
)
SELECT tmp.customerid, tmp.denomid,
       su.quantity,
       tmp.cus_name,
       tmp.denom,
       tmp.currency
FROM   tmp
INNER  JOIN stockupdations su
ON     tmp.customerid = su.custid
AND    tmp.denomid = su.denomid
AND    tmp.curid = su.curid
于 2010-10-13T07:08:23.307 回答
0

您可以在from子句中使用“内部查询”,而不是在select.

假设我有一个 CUSTOMER 表和 ORDER 表,

我可以有类似的东西

SELECT C.CUSTOMER_ID, COUNT(T.ORDER_ID)
FROM CUSTOMERS C
JOIN (SELECT CUSTOMER_ID, ORDER_ID, ORDER_DATE, ORDER_STATUS FROM ORDERS O WHERE O.STATUS <> 'DECLINED') T
ON T.CUSTOMER_ID = C.CUSTOMER ID
GROUP BY C.CUSTOMER_ID

(这个 SQL 只是一个例子,我知道有更好的方法来写这个,但我想不出任何其他的例子)

于 2010-10-13T07:18:24.317 回答