我已經看到使用 max(value) 和 group by 來選擇重復 ID 的最高值(SQL 選擇重復 ID 的最高值)的查詢,但是,我相信我沒有正確應用該方法,并希望有人可以提供幫助。
我需要做一個 select into 陳述句,因為我稍后會參考這個表。記住這一點,我的代碼如下所示:
select class, record_id, max(salesprice) as salesprice, category, zone
into ##weeklysalestable
from ##salestable
where class in ('residential')
group by class, record id, category, zone
order by record_id, class, category,zone
問題是 SQL 提示我命名第 3 列(所以我將其添加到上面的代碼中),然后我認為這導致輸出不會洗掉具有較低銷售價格的重復項。目標只是保持銷售價格最高的record_id。
在這種情況下不能應用 max() 嗎?如果是這樣,是否有替代方法?
示例源資料:
| 班級 | 記錄編號 | 銷售價格 | 類別 | 區 |
|---|---|---|---|---|
| A1 | AR2695 | 13 | 新的 | 東北部 |
| A1 | AR2695 | 26 | 新的 | 東北部 |
| B2 | AL5397 | 18 | USL | 東南 |
| C3 | AM3920 | 39 | 新的 | 西南 |
期望的輸出:
| 記錄編號 | 班級 | 銷售價格 | 類別 | 區 |
|---|---|---|---|---|
| AR2695 | A1 | 26 | 新的 | 東北部 |
| AL5397 | B2 | 18 | USL | 東南 |
| AM3920 | C3 | 39 | 新的 | 西南 |
任何建議都會很棒。
uj5u.com熱心網友回復:
一種選擇是row_number() over()在子查詢中使用視窗函式
select class,
record_id,
salesprice,
category,
zone
into ##weeklysalestable
from ( Select *
,rn = row_number() over (partition by class,category,zone order by salesprice desc) -- assuming `record_id` doesn't need to be in the `partition`
From ##salestable
where class in ('residential')
) A
Where RN = 1
另一種選擇是使用WITH TIES (輕推性能較差)
select top 1 with ties
class,
record_id,
salesprice,
category,
zone
into ##weeklysalestable
from ##salestable
where class in ('residential')
order by row_number() over (partition by class,category,zone order by salesprice desc) -- assuming `record_id` doesn't need to be in the `partition`
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/404946.html
標籤:
上一篇:如何修復“TypeError:串列索引必須是整數或切片,而不是str”
下一篇:在第二天上午10點之前檢查資料
