簡體   English   中英

如何在 WHERE 中使用 HAVING SUM() 並僅選擇 db2 上的某些行來 select 不屬於聚合查詢的列

[英]How to select columns that aren't part of an aggregate query using HAVING SUM() in the WHERE and selecting only certain rows on db2

為此使用 AS400 db2。

我有一張訂單表。 從那張桌子上,我必須:

  • 從指定的訂單 ID 列表中獲取所有訂單並輸入
  • 按這些訂單上的 user_id 分組
  • 檢查以確保該組的總訂單金額大於 100 美元
  • 返回所有匹配該組但結果不會被分組的訂單,其中包括不屬於該組的order_id

我有點卡住了,因為 AS400 不喜歡我要求 select 一個不屬於我需要的組的字段。

我想出了這個查詢,但它很慢。

-- Create a common temp table we can use in both places
WITH wantedOrders AS (
SELECT order_id FROM orders
WHERE
-- Only orders from the web
order_type = 'web'
-- And only orders that we want to get at this time
AND order_id IN
    (
        50,
        20,
        30
    )
)
-- Our main select that gets all order information, even the non-grouped stuff
SELECT
    t1.order_id,
    t1.user_id,
    t1.amount,
    t2.total_amount,
    t2.count
    
FROM orders AS t1
-- Join in the group data where we can do our query
JOIN (
    SELECT 
    user_id,
    SUM(amount) as total_amount,
    COUNT(*) AS count
    FROM
    orders
-- Re use the temp table to get the order numbers
    WHERE order_id IN (SELECT order_id FROM wantedOrders)
    GROUP BY
    user_id
    HAVING SUM(amount)>100
) AS t2 ON t2.user_id=t1.user_id
-- Make sure we only use the order numbers
WHERE order_id IN (SELECT order_id FROM wantedOrders)
ORDER BY t1.user_id ASC;

編寫此查詢的更好方法是什么?

嘗試這個:

WITH 
  wantedOrders (order_id) AS
  (
    VALUES 1, 2
  )
, orders (order_id, user_id, amount) AS
  (
    VALUES
      (1, 1, 50)
    , (2, 1, 50)
    , (1, 2, 60)
    , (2, 2, 60)

    , (3, 3, 200)
    , (4, 3, 200)
   )
-- Our main select that gets all order information, even the non-grouped stuff
SELECT *
FROM
(
  SELECT
    order_id,
    user_id,
    amount,
    SUM   (amount) OVER (PARTITION BY user_id) AS total_amount,
    COUNT (*)      OVER (PARTITION BY user_id) AS count
  FROM orders t
  WHERE EXISTS 
  (
    SELECT 1 
    FROM wantedOrders w 
    WHERE w.order_id = t.order_id
  )
) A
WHERE total_amount > 100
ORDER BY user_id ASC
ORDER_ID 用戶身份 數量 總金額 數數
1 2 60 120 2
2 2 60 120 2

如果 order_id 是表的 PK。 然后只需將您需要的列添加到 WantOrders 查詢並將其用作您的“基礎”(而不是使用訂單並重新過濾它。您最終應該加入 WantOrders 本身。

你可以做:

select t.*
from orders t
join (
  select user_id
  from orders t
  where order_id in (50, 20, 30)
  group by user_id
  having sum(total_amount) > 100
) s on s.user_id = t.user_id

第一個表orders as t將生成您想要的數據。 它將由根據您的邏輯預先選擇組s第二個“表表達式”過濾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM