There are a couple of ways you can do this, but the basic premise is the same. Find each B & MAX(A) combination and join this result set back to your source table on those columns to return the UID. This db<>fiddle highlights two possible, simple solutions.
The code for each:
/* Option #1 */
WITH MaxBs AS (
SELECT B, MAX(A) AS A
Pls have a look at this for bit more understanding on GROUP.
GROUP BY (even with GROUPING SET) clause required all the column to be included that are mentioned in SELECT clause excluding the ones inside aggregation function (in your case SUM).
Hope following is the one that you looking for, for more examples and test:
SELECT Branch, CustCode, name,
If you create a user function (or 2), some parts of your 'problem' can be solved:
DROP FUNCTION IF EXISTS clamp(val numeric);
CREATE FUNCTION clamp(val numeric) RETURNS bigint AS $$
RETURN CASE WHEN val>+9223372036854775807 THEN +9223372036854775807 WHEN val<-9223372036854775808 THEN -9223372036854775808 ELSE val::bigint END;
Generic code for calculating 1,2,3,4,..6,...12 years / quarters / months / weeks / days /hours moving average, median, percentiles, etc. summary stats where table contains a list of individual time records (like sales transactions,etc)
WITH grid AS (
SELECT end_time, start_time
, lag(end_time, 12, '...
Get rid of @num_rows and @i; you can loop without counting. There are lots of examples floating around.
You must construct the query something like
SET @stmt := CONCAT('SELECT "', col_name, '", ' MIN(', col_name, '), ',
' MAX(', col_name, ')',
' FROM ', tbl_name');
The intent is to ...