Pages

Tuesday, October 18, 2011

SQL Condition in SELECT Query

Sometimes we need to check some condition in SQL SELECT query. Today I am going to show you the way of this by en example.
Let we have a table as follow:

Let we have to show a table where credit and debit will be summed and there will be two more row named CREDITFINAL and DEBITFINAL.
Let,
  • sum of Credit for Head X is CX
  • sum of Debit for Head X is DX
Now
  • CREDITFINAL will contain the data if CX>DX with value CX-DX
  • DEBITFINAL will contain the data if DX>=CX with value DX-CX
To show data such way we need to check condition in SQL SELECT statement. Now I am going to perform this task step by step so that you will understand easily.

First Let show only the column HeadID, HeadName, Credit & Debit. For this our query will be as follow:-

SELECT [HeadID] 
      ,[HeadName] 
      ,[Date] 
      ,[Credit] 
      ,[Debit] 
FROM [sql_condition]

Output will be as follow:


Now Let we will show the data by summing the CREDIT and DEBIT of same type, means same HeadID and HeadName.







Output will be as follow:-






Here sum of CREDIT for any Head will be show in column name CREDITSUM, because I use AS.


Now I am going to perform my main task.

  • CREDITFINAL will contain the data if   CX>DX   with value CX-DX
  • DEBITFINAL    will contain the data if   DX>=CX  with value DX-CX

Here I am going to USE CAST, you can find more help, Click Here.

Syntax for CAST:
CAST ( expression AS data_type [ ( length ) ] )


For perform condition here I am going to use CASE, which syntax is given bellow
CASE expression 
     WHEN expression1 THEN result_expression1 
     WHEN when_expression2 THEN result_expression2
     ................... 
     [ ELSE else_result_expression ] 
END 
Searched CASE expression:
CASE
     WHEN Boolean_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END
And My query is as follow for the final task.


And the output is as follow


Any kind of advice is appreciated.
Thanks.

2 comments:

Kevin L. said...

Thanks Razib..

Excellent post..

Razib Deb said...

You are Welcome Kevin.
And Thanks for your comment.