Oracle

根據聚合函式 sum() 結果連接兩個表

  • December 20, 2019

我有一個與基於結果連接兩個表有關的小問題。SUM()以下是我的表。

Customers Table  

CUSTOMERID      NAME AGE   ADDRESS       PHONE
       1        AA  33    Some Address  123654789
       2        BB  35    Some Address  123654789
       3        CC  55    Some Address  987654789
       4        DD  55    Some Address  987654789
       5        EE  25    Some Address  365754789
       6        FF  20    Some Address  365754789


Orders Table 

   ORDERID  CUSTOMERID ORDERAMOUNT
   C12335    3         50000
   F12336    3         12000
   C12337    3         5000
   C12338    1         3700
   C12339    2         1100

我顯示了 ORDERAMOUNT 總和超過 50000 的客戶的 customerID,Name,Address,Sum of order。

但是,由於我不能像SUM()WHERE子句之後那樣使用聚合函式,所以我在這裡遇到了麻煩。

SELECT C.NAME,C.ADDRESS,O.CUSTOMERID
FROM CUSTOMERS C
INNER JOIN
(
   SELECT CUSTOMERID,SUM(ORDERAMOUNT) AS sumorders FROM ORDERS GROUP BY CUSTOMERID
)O ON C.CUSTOMERID = O.CUSTOMERID;

我能寫的最先進的工作查詢是這個,它不評估Sum of ORDERAMOUNT is more than 50000.

有沒有辦法我也可以評估這種情況?非常感謝您的幫助。提前致謝 :)

不能在 WHERE 子句中使用 SUM。但是,您可以在 HAVING 中使用它

SELECT C.NAME,C.ADDRESS,O.CUSTOMERID
FROM CUSTOMERS C
INNER JOIN
(
   SELECT CUSTOMERID,SUM(ORDERAMOUNT) AS sumorders 
   FROM ORDERS 
   GROUP BY CUSTOMERID 
   HAVING SUM(ORDERAMOUNT)>5000
)O ON C.CUSTOMERID = O.CUSTOMERID;

使用“有”

聲明@Customers 表
(
customerid int,
名稱 varchar(30),
年齡整數,
地址 varchar(100),
電話 varchar(100)
)


聲明@Orders 表
(
orderid varchar(10),
customerid int,
訂單金額小數(18,2)
)

插入@Customers
(
客戶ID,
name,
年齡,
地址,
電話
)
價值觀

(1, 'AA', 33, '某個地址', '123654789'),
(2, 'BB', 35, '某個地址', '123654789'),
(3, '抄送', 55, '某個地址', '987654789'),
(4, 'DD', 55, '某個地址', '987654789'),
(5, 'EE', 25, '一些地址', '365754789'),
(6, 'FF', 20, '某個地址', '365754789')

插入@Orders
(
訂單號,
客戶ID,
訂單金額
)
價值觀
('C12335',​​ 3, 50000),
('F12336', 3, 12000),
('C12337', 3, 5000),
('C12338', 1, 3700),
('C12339', 2, 1100)




選擇 c.customerid、c.name、c.address、sum(o.orderamount) sumorders
FROM @Customers c INNER JOIN @Orders o ON c.customerid = o.customerid
按 c.customerid、c.name、c.address 分組
總和(o.orderamount)> 50000

引用自:https://dba.stackexchange.com/questions/186532