Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

postgresql - How to remove unknown entries and distribute its numeric value across other known entries?

I've been trying to wrap my head around this, but I cannot seem to find an easy solution:

I have a table with known and unknown entries. Each entry has a column with a numeric value representing it. How do I remove the unknown entries, and equally distribute its numeric value across other known entries?

Here is an example:

Original table:

|Item | Size | Count |
|-----|------|-------|
|A    | null |  20   |
|A    | M    |   5   |
|A    | XL   |  10   |
|B    | null |  12   |
|B    | M    |  8    |

Desired output:

|Item | Size | Count |
|-----|------|-------|
|A    | M    |  15   |
|A    | XL   |  20   |
|B    | M    |  20   |

Basically, I want to remove the items with null sizes, and evenly distribute its count across other sizes for that same item.

Would be great if I could get some help! Thanks in advance


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

step-by-step demo:db<>fiddle

SELECT 
    item,
    size,
    cnt + (sum / count)                 -- 2
FROM (
    SELECT                              -- 1
        *,
        SUM(cnt) FILTER (WHERE size IS NULL) OVER (PARTITION BY item),
        COUNT(cnt) FILTER (WHERE size IS NOT NULL) OVER (PARTITION BY item)
    FROM
        mytable
) s
WHERE size IS NOT NULL                  -- 3
  1. Use SUM() and COUNT() window functions to find the amount to split up (= all cnt values of NULL records) and the number of split parts (= all non-NULL records).
  2. Add the split parts to the current cnt value
  3. Filter all non-NULL records

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...