I have a table like this:
I need to find the max value of num_trans for each account and also the corresponding operator_id.
So I write something like this:
I get these results:
For account_id = 1 I get the result that I wanted.
For account_id = 2 I get 2 rows.
This result makes sense, since there are 2 operators that have num_trans = max_num_trans. However this is not what I want. I want for every account to get only one row. If there are 2 or more rows that have the max value only one would be selected somehow (I do not care which one).
So in the above case I would like to get:
or:
Ideas?
Code:
DECLARE @operator_activity TABLE (
account_id INT,
operator_id INT,
num_trans INT
)
So I write something like this:
Code:
DECLARE @operator_activity TABLE (
account_id INT,
operator_id INT,
num_trans INT
)
INSERT INTO @operator_activity VALUES (1, 1, 1)
INSERT INTO @operator_activity VALUES (1, 2, 1)
INSERT INTO @operator_activity VALUES (1, 3, 2)
INSERT INTO @operator_activity VALUES (2, 2, 1)
INSERT INTO @operator_activity VALUES (2, 4, 1)
SELECT oa.account_id,
max_num_trans,
operator_id
FROM @operator_activity oa
JOIN (
SELECT account_id,
MAX(num_trans) AS max_num_trans
FROM @operator_activity
GROUP BY account_id) AS A
ON oa.account_id = A.account_id
WHERE num_trans = max_num_trans
Code:
account_id max_num_trans operator_id
----------- ------------- -----------
2 1 2
2 1 4
1 2 3
For account_id = 2 I get 2 rows.
This result makes sense, since there are 2 operators that have num_trans = max_num_trans. However this is not what I want. I want for every account to get only one row. If there are 2 or more rows that have the max value only one would be selected somehow (I do not care which one).
So in the above case I would like to get:
Code:
account_id max_num_trans operator_id
----------- ------------- -----------
2 1 2
1 2 3
Code:
account_id max_num_trans operator_id
----------- ------------- -----------
2 1 4
1 2 3
Ideas?