[英]Sorting sub-queries in SQL
我一直在嘗試在SQL 2012中工作的查詢,我幾乎可以肯定我已經使它復雜化了
我有一個表,其中存儲一個訂單號,商品編號(每個訂單多個),狀態碼(每個商品多個)和時間戳
所以基本上是這樣的
Order Item Status
1 1 1
1 1 2
2 1 1
2 1 2
2 1 3
3 1 3
3 2 1
3 2 2
在我的查詢中(以該表為例),我需要為每個行和每個項目查看以下1個條目,但僅顯示最高可用狀態...但是如果狀態為3,則不會
所以在這種情況下,我想看看
Order Item Status
1 1 2
3 2 2
我遇到的問題是查詢本身可以工作...但是它返回找到的第一個狀態代碼。 不是最高的。 所以我最終
Order Item Status
1 1 1
3 2 1
這是完整的擴展代碼段
with summary as (
select a.order_no as order_no, a.item_no as item_no, a.timestamp as timestamp,
max(a.status_code) as status_code, row_number() over (partition by order_no
order by item_no asc) as rn
from db.ordhist a
where a.order_no > 120400000 and a.order_no < 120800000
and a.timestamp < Dateadd(DD,-3,GETDATE() )
and a.status_code >= 133
and not exists (
select b.order_no, b.item_no
from db.ordhist b
where b.status_code in (137,170,201,999)
and b.order_no = a.order_no
and b.item_no = a.item_no)
and not exists (
select c.order_no
from db.ordhist c
where c.status_code = 6
and c.order_no = a.order_no)
group by a.order_no, a.item_no, a.timestamp)
select * from summary where rn = 1
我認為您不需要ROW_NUMBER
只需將GROUP BY
與HAVING MAX([Status])<>3
:
SELECT [Order],[Item],MAX([Status])
FROM Table_Name
GROUP BY [Order],[Item]
HAVING MAX([Status])<>3
好的,我想我可能已經回答了我自己的問題...。通過刪除“摘要”中的分組並在最終結果查詢中進行分組
-- Produced (or higher) but not Delivery Noted --
with summary as (
select a.order_no as order_no, a.item_no as item_no, a.timestamp as timestamp, a.status_code as status_code
from db.ordhist a
where a.order_no > 120400000 and a.order_no < 120800000
and a.timestamp < Dateadd(DD,-3,GETDATE() )
and a.status_code >= 133
and not exists (
select b.order_no, b.item_no
from db.ordhist b
where b.status_code in (137,170,201,999)
and b.order_no = a.order_no
and b.item_no = a.item_no)
and not exists (
select c.order_no
from db.ordhist c
where c.status_code = 6
and c.order_no = a.order_no))
select order_no, item_no, timestamp, max(status_code) from summary
group by order_no, item_no, timestamp
order by status_code
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.