简体   繁体   中英

Compare aggregate of column with another column of same table

I have a table D_MARK with following layout,

+---------+-----------+-------------------------+
| CLAS_ID | MARK      | MARK_THRESHOLD          |
+---------+-----------+-------------------------+
| 9001    |         5 |                    10   |
| 9001    |        10 |                    10   |
| 9004    |         5 |                    10   |
+---------+-----------+-------------------------+

I'm trying to create a View from this table based on following logic:-

1.Need to do sum( MARK ) group by CLAS_ID .

2.Need to showcase sum( MARK ) as FINAL_MARK such that, if sum(MARK) > MARK_THRESHOLD then MARK_THRESHOLD else sum(MARK)

Expected Output:-

+---------+-----------+
| CLAS_ID | FINAL_MARK|
+---------+-----------+
| 9001    |        10 |
| 9004    |         5 |
+---------+-----------+

So this is what I've done so far,

CREATE VIEW V1 AS SELECT CLAS_ID, SUM(CASE WHEN SUM(MARK) > MARK_THRESHOLD THEN MARK_THRESHOLD ELSE SUM(MARK) END) AS FINAL_MARK 
FROM `D_MARK` GROUP BY CLAS_ID;

On executing this I'm getting, Invalid use of group function error. I'm guessing using an aggregate function within case is a big no?

So I was wondering if someone could help me out a bit as I'm pretty new to this. Thanks in advance.

PS MARK_THRESHOLD will be the same for a particular CLAS_ID .

Aggregate also with MAX() (or MIN() it does not matter) on MARK_THRESHOLD :

CREATE VIEW V1 AS 
SELECT CLAS_ID, 
       LEAST(SUM(MARK), MAX(MARK_THRESHOLD)) AS FINAL_MARK 
FROM D_MARK 
GROUP BY CLAS_ID

Use the function LEAST() instead of the CASE expression.
See the demo .
Results:

| CLAS_ID | FINAL_MARK |
| ------- | ---------- |
| 9001    | 10         |
| 9004    | 5          |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM