简体   繁体   中英

Select distinct row based on highest absolute value

I a MSAccess database which contains the following table

Table A

#

Column1 Column2 Amount
======= ======= ======
Value1 Total+ 100
Value1 Total- -50
Value2 Total- -233
Value2 Total+ +5

I want to be write a query that will give me distinct rows for the highest absolute amounts

Expected Results
Column1 Column2 Amount
======= ======= ======
Value1 Total+ 100
Value2 Total- -233

This result set can be retrieved with the following query.

Column1 max_abs_value
Value1            100
Value2            233

SELECT
    Column1,
    Max(Abs(Amount)) AS max_abs_value
FROM Table_A
GROUP BY Column1;

Then, if you want to see the values of Column2 and Amount for those same rows, you can create a query which uses the first one as a subquery and which you join to Table_A .

SELECT
    a.Column1,
    a.Column2,
    a.Amount
FROM
    Table_A AS a
    INNER JOIN (
        SELECT
            Column1,
            Max(Abs(Amount)) AS max_abs_value
        FROM Table_A
        GROUP BY Column1
    ) AS sub
    ON a.Column1 = sub.Column1
WHERE
    Abs(Amount)=sub.max_abs_value;

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