Monday, May 30, 2016

How to get unmatched rows from two tables

Let Create  two tables

create table t1 (Id int, name varchar(50))
create table t2 (Id int, name varchar(50))

insert t1 values (1,       'avi')
insert t1 values (2,      'ravi')
insert t1 values (3,       'sun')
insert t1 values (5,       'naveen')
insert t1 values (7,       'rachin')

insert t2 values (1,       'avi')
insert t2 values (2,       'ravi')
insert t2 values (4,       'naveen')
insert t2 values (6,       'raja')


Query to find unmatched rows 

Option 1:
Select Id, Name
from T1
where Id not in (select Id from T2)
UNION
Select Id, Name
from t2

where Id not in (select Id from t1)

Option 2:

select isnull(t1.id, t2.id), isnull(t1.name,t2.name)  from t1
full outer join t2 on t1.id = t2.id
where t2.Id is null or t1.id is null



Monday, May 16, 2016

How to calculate running total

How to calculate running total ?

create table store(Id int primary key,productname varchar(20), sales int)

insert into store values (101,'grapes', 4000),
(102,'apples', 10000),
(103,'carrot', 14000),
(104,'watermelon', 9000),
(105,'mangoes', 12000)

select * from  store

Below is the query to find the running total sales 


 select ID,  productname,sales
 ,(select sum(sales) from store 
 where ID <= S.ID)
 'Running Total'
from store S

How to find a Leap year by using User Defined functions

Leap year by using User Defined functions



Function:


CREATE  FUNCTION [dbo].[LeapYear] ( @Date    DATETIME )
RETURNS VARCHAR(100)
AS
BEGIN

    IF (YEAR( @Date ) % 4 = 0 AND YEAR( @Date ) % 100 != 0) OR
        YEAR( @Date ) % 400 = 0

        RETURN 'Leap Year'

    RETURN 'Non-Leap Year'

END
GO

To execute the above function 

select [dbo].[LeapYear] ('2016')


Once you practice delete all these stuff 


 drop function [dbo].[LeapYear]