Showing posts with label Group by. Show all posts
Showing posts with label Group by. Show all posts

Thursday, July 21, 2011

Group By VS Distinct in SQL


Group by VS Distinct

Group By : The SQL GROUP BY statement is used together with the SQL aggregate functions to group the retrieved data by one or more columns. 
Distinct : The DISTINCT keyword can be used to return only distinct (different) values.

Orders table :
OrderId
PersonName
Price
Quantity
101
John
12
1
102
Sam
4
1
103
John
14
2
104
Brendon
12
1
106
Allen
2
11
107
Allen
3
11

Query 1: Select PersonName,Price from Orders group by PersonName,Price
Query 2:Select distinct PersonName,Price from Orders

Execution plan for both queries are same and return 5 records.

But the purpose of Group by is different it is used to group the records and apply aggregate function on it.

Query 3: Select PersonName,Sum(Price) as ‘Total’ from Orders group by PersonName

Query 3 returns only for records like below
PersonName
Total
Allen
5
Brendon
12
John
26
Sam
4

Wednesday, July 20, 2011

SQL Group By


Group By in SQL:

The SQL GROUP BY statement is used together with the SQL aggregate functions to group the retrieved data by one or more columns. 

Example :

Sales(OrderId,Customer,Price,Date)

1.Select Customer,sum(price) from Sales group by Customer