I have this table:
I want to write a query that selects the accounts, the total transaction amounts and the number of times the transaction amount was > 1.
This query:
gives this result:
This query:
gives me this result:
Neither gives me the right result. The result must be:
Ideas?
Code:
DECLARE @transactions TABLE (account_id INT, amount INT)
INSERT INTO @transactions VALUES (1, 1)
INSERT INTO @transactions VALUES (1, 2)
INSERT INTO @transactions VALUES (1, 3)
INSERT INTO @transactions VALUES (2, 2)
INSERT INTO @transactions VALUES (2, 2)
This query:
Code:
SELECT account_id,
COUNT(*) AS num_high_trans,
SUM(amount) AS total_amount
FROM @transactions
WHERE amount > 1
GROUP BY account_id
HAVING count(*) > 1
Code:
account_id num_high_trans total_amount
----------- -------------- ------------
1 2 5
2 2 4
Code:
SELECT account_id,
COUNT(*) AS num_high_trans,
SUM(amount) AS total_amount
FROM @transactions
GROUP BY account_id
HAVING count(*) > 1
Code:
account_id num_high_trans total_amount
----------- -------------- ------------
1 3 6
2 2 4
Code:
account_id num_high_trans total_amount
----------- -------------- ------------
1 2 6
2 2 4