You are on page 1of 2

#1 Print star patter in SQL

=============================
declare @var int
set @var = 1
while @var <= 20
begin
print replicate('* ', @var)
set @var = @var + 1
end

o/p:
-----
*
* *
* * *
* * * *
* * * * *

#2 Print Prime Numbers


=========================
Declare @Count int = 2;
Declare @Number int = 3;
Declare @IsPrimeNo Bit = 1;
Declare @Output varchar(max) = '2';

while @Number <= 1000


Begin
set @IsPrimeNo = 1
set @Count = 2
while(@Count < @Number)
Begin
if(@Number % @Count = 0)
Begin
set @IsPrimeNo = 0
break
End
set @Count = @Count + 1
End
If(@IsPrimeNo=1)
Begin
set @Output = @Output + '&' + Cast(@Number as varchar(255))
End
set @Number = @Number + 1
End

print @Output;

#3 LEFT JOIN & HAVING BY


=========================
Carefully use type of join mostly mind go for inner join but see if it is question
of left join otherwise we will miss
records
Also ,while doing aggregations to filter agg. records use having clause

#4 CASE WHEN
=========================
You can use case when statement inside aggregate functions
eg: select s.user_id,
sum(case when c.action='confirmed' then 1 else 0 end ) as confirmed_count,
count(*) as total_requests
from Signups s left join Confirmations c
on s.user_id = c.user_id
group by s.user_id

#5 Dividing integers/CAST Function


===================================
if you are diving integers then it will give integer only eg: 1/2 gives 0 insted of
0.5
so to resolve this multiply one value by 1.0
eg: 1*1.0/2 = 0.5

Alternatively, we can cast value as float

#6 FORMAT DATE INTO SPECIFIC FORMAT


=====================================
format(trans_date,'yyyy-MM')

select id,
case when id%2<>0 and next_student is null then student
case when id%2<>0 then next_student
case when id%2=0 then prev_studnet
end as student
from
(
select id,
student,
lag(student) over (order by id asc) as prev_student,
lead(student) over (order by id asc) as next_student
from Seat
) a
order by id

You might also like