如何在SQL中为每个ID分组计算并展示最大Outstanding值
SQL Query to Add MAX_OUTSTANDING Column per ID
Got it, here's a straightforward solution using SQL window functions to get exactly the result you need:
Original Table (Table1)
| outstanding | month | year | ID |
|---|---|---|---|
| 5000000 | 07 | 2017 | 1234 |
| 4000000 | 08 | 2017 | 1234 |
| 6000000 | 09 | 2017 | 1234 |
| 4500000 | 10 | 2017 | 1234 |
| 500000 | 08 | 2017 | 1235 |
| 700000 | 09 | 2017 | 1235 |
| 4500000 | 07 | 2017 | 1236 |
| 3000000 | 08 | 2017 | 1236 |
| 4800000 | 09 | 2017 | 1236 |
| 4500000 | 10 | 2017 | 1236 |
Requirement
Query all fields from Table1, and add a
MAX_OUTSTANDINGcolumn that shows the maximum value ofoutstandingfor each correspondingID.
Solution Query
SELECT outstanding, month, year, ID, MAX(outstanding) OVER (PARTITION BY ID) AS MAX_OUTSTANDING FROM Table1;
How This Works
The MAX(outstanding) OVER (PARTITION BY ID) part is a window function:
MAX(outstanding)calculates the highest value in theoutstandingcolumnPARTITION BY IDsplits the data into groups based on each uniqueID, so the max is calculated per ID- Unlike a regular
GROUP BYwhich would collapse rows into a single row per group, this window function preserves all original rows while attaching the correct max value to every row in the group.
Expected Result
| OUTSTANDING | MONTH | YEAR | ID | MAX_OUTSTANDING |
|---|---|---|---|---|
| 5000000 | 07 | 2017 | 1234 | 6000000 |
| 4000000 | 08 | 2017 | 1234 | 6000000 |
| 6000000 | 09 | 2017 | 1234 | 6000000 |
| 4500000 | 10 | 2017 | 1234 | 6000000 |
| 500000 | 08 | 2017 | 1235 | 700000 |
| 700000 | 09 | 2017 | 1235 | 700000 |
| 4500000 | 07 | 2017 | 1236 | 4800000 |
| 3000000 | 08 | 2017 | 1236 | 4800000 |
| 4800000 | 09 | 2017 | 1236 | 4800000 |
| 4500000 | 10 | 2017 | 1236 | 4800000 |
内容的提问来源于stack exchange,提问作者mae
相关产品推荐
相关产品推荐

