[英]Using DB2 SQL, how can I avoid returning rows that aren't the most recent, for a condition that is NOT part of my where clause?
[英]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。
我有一張訂單表。 從那張桌子上,我必須:
我有點卡住了,因為 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.