Group By TSQL Tutorial

Group By is used when we have an aggregate function(like: count, max, min, sum, avg) in our query. In first example the order is random, in second example we use the column amount for the order.

CONTRACT_IDAMOUNT
1400
2500
3700
4500
1400
5200

Group By Example 1:

SELECT c.contract_id, c.amount, COUNT(c.contract_id) AS CtrCount
   FROM contracts c
GROUP BY c.contract_id, c.amount;

Contract_IdAmountCtrCount
52001
14002
25001
45001
37001

Group By Example 2:

SELECT c.contract_id, c.amount, COUNT(*) AS CtrCount
  FROM contracts c
GROUP BY c.amount, c.contract_id
ORDER BY c.amount;

Contract_IdAmountCtrCount
52001
14002
25001
45001
37001