WHERE Clause in SQL with GROUP BY
WHERE clause in SQL with GROUP BY is used to extract only those records that fulfil a specified condition. Condition on any dimension or fields available within a Table.
Where clause is very useful and powerful command used in SQL query to extract data from huge Sample of data. It is used in SELECT command of SQL.
Below we will go through the normal where clause command syntax and with examples and then we will look how GROUP BY command can be applied on WHERE clause
WHERE Syntax:
SELECT
column1, column2, ...
FROM
table_name
WHERE
condition;
Example #1: WHERE condition on one column
Lets Take example to Filter on Product_Category equal to Furniture
SELECT
*
FROM
[dbo].[Customers_Tbl]
WHERE
[Product_Category] = 'Furniture'
Result:
Example #2: WHERE clause for two condition using Logical Function “AND”
Filter on Furniture which have Margin greater then 70%. In this example we are applying WHERE clause for two condition using Logical Function “AND”
SELECT
[Product_Category], Region,[Product_Base_Margin]
FROM
[dbo].[Customers_Tbl]
WHERE
([Product_Category] = 'Furniture')
AND
([Product_Base_Margin] > 0.70
Result:
GROUP BY
Now lets understand Where clause in SQL with GROUP BY
GROUP BY is the command which used to make the output in aggregated way.
The GROUP BY clause arrange the rows members by groups (It is like a Pivot to grouping columns member to see aggregated value). The groups are determined by the columns that you specify in the GROUP BY clause.
Syntax:
SELECT
select_list
FROM
table_name
WHERE Condition
GROUP BY
column_name1,
column_name2, ..
Example #1: Query to extract data from table with group by Clause
Below Query Product_Category is appear only For individual Product_Container
SELECT Product_Category, Product_Container FROM [dbo].[Customers_Tbl] WHERE ([Product_Category] = 'Furniture') OR ([Product_Category] = 'Office supplies') GROUP BY Product_Category, Product_Container
Result:
Example #2: GROUP BY clause and aggregate functions without WHERE clause
b) SQL Server GROUP BY clause and aggregate functions without WHERE clause
SELECT [Order Priority], Sum([Order Quantity]) as order_Quantity FROM [dbo].[Orders_Tbl] GROUP BY [Order Priority]
Result: Here Order quantity is summed up by order Priority