我有下表
| 物品 | 區域 | 數量 |
|---|---|---|
| 第 1 項 | 一個 | 10 |
| 第 1 項 | b | 17 |
| 第 2 項 | b | 20 |
| 第 3 項 | 一個 | 10 |
| 第 2 項 | C | 8 |
我希望在 sql 中得到如下結果(一個獨特的專案和一個獨特的區域):
| 物品 | a區 | b區 | c區 |
|---|---|---|---|
| 第 1 項 | 10 | 17 | 0 |
| 第 2 項 | 0 | 20 | 8 |
| 第 3 項 | 10 | 0 | 0 |
我確實有這個查詢,如果該區域已更改或增加,它并沒有給我正在尋找的內容,它也適用于 2 串列而不是 3 列:
select
item,
max(case when seqnum = 1 then area end) as area_1,
max(case when seqnum = 2 then area end) as area_2,
max(case when seqnum = 3 then area end) as area_3
from (
select A.*,
row_number() over (partition by item order by area) as seqnum
from A
) A
group by item;
期待您的熱心幫助
我嘗試修改現有的查詢,尋求幫助來修改和理解我所缺少的,以便對未來有更多的了解
uj5u.com熱心網友回復:
如果您有固定的區域串列,則不需要視窗函式;您可以顯式過濾max().
對查詢的另一個修復是取最大值qty而不是area(其值已被過濾)。
select item,
coalesce(max(case when area = 'a' then qty end), 0) as area_a,
coalesce(max(case when area = 'b' then qty end), 0) as area_b,
coalesce(max(case when area = 'c' then qty end), 0) as area_c
from mytable
group by item
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/524328.html
