Click here to Skip to main content
15,884,176 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have table names 'payroll' with following data

month , pay
January , 1200
March , 1500
December , 2000


I want the following result

Janury , 1200
February , 00
March , 1500
April , 00
May , 00
June , 00
July , 00
August , 00
September , 00
October , 00
November , 00
December , 00
Posted
Updated 12-Jun-13 8:51am
v2
Comments
Mike Meinz 12-Jun-13 6:05am    
Is this homework?
allagi.arun 12-Jun-13 6:13am    
Nope
allagi.arun 12-Jun-13 6:14am    
Do you know the answer
Mike Meinz 12-Jun-13 6:18am    
Twelve SELECT statements using UNION to merge the results together. Use ISNULL function when selecting pay column to return 0 instead of NULL.

Hi Friend,
Try this code
SQL
SELECT * INTO #tmppay 
from (
SELECT number, DATENAME(MONTH, '2012-' + CAST(number as varchar(2)) + '-1') monthname,'00' as pay
FROM master..spt_values
WHERE Type = 'P' and number between 1 and 12
) as tp1
select tmp.[monthname], isnull(p.Pay,00) from #tmppay tmp 
left  outer JOIN  pay p on tmp.[monthname]=p.[month]
drop TABLE #tmppay
 
Share this answer
 
Hi Friend,

you can try the alternate of above code

SQL
with TempPay(number,[monthname],pay)
as
(
SELECT number, DATENAME(MONTH, '2012-' + CAST(number as varchar(2)) + '-1') monthname,00 as pay
FROM master..spt_values
 --inner join pay on [month]= [monthname]
WHERE Type = 'P' and number between 1 and 12

)
select tp.[monthname], isnull(p.Pay,0) as pay from TempPay tp

LEFT outer JOIN  pay p on p.[month]=tp.[monthname]
 
Share this answer
 
Hi,

You can try like this also....
SQL
SELECT T.monthname 'Month', ISNULL(P.pay,0) 'Pay'
FROM payroll P
LEFT OUTER JOIN (SELECT DATENAME(MONTH, '2013-' + CAST(number as varchar(2)) + '-1') monthname
                 FROM master..spt_values  
                 WHERE Type = 'P' and number between 1 and 12) ON T.monthname=P.month

Regards,
GVPrabu
 
Share this answer
 
v2
Hi,

try this solution.


SQL
;WITH MonthPayCTE AS
(
 SELECT 0 monthOrder, DateAdd(d, -DatePart(dy,getdate()-1),getdate()) as PayMonth
 UNION ALL
 SELECT MonthPayCTE.monthOrder+1 , DATEADD(m,1,MonthPayCTE.PayMonth) As PayMonth
 FROM MonthPayCTE WHERE PayMonth < DateAdd(d, -DatePart(d,getdate()), 
 Dateadd(m,12-datepart(m,getdate()),getdate()))
)


SELECT  A.Month,ISNULL(A.Pay,0) As Pay FROM (
 SELECT ROW_NUMBER() OVER(Partition By MonthPayCTE.PayMonth,PayRoll.Pay 
 Order By MonthPayCTE.PayMonth) RowNum, DATENAME(month, MonthPayCTE.PayMonth) As Month,
 Payroll.Pay FROM Payroll RIGHT OUTER JOIN MonthPayCTE 
 ON  LTRIM(RTRIM(DATENAME(month,MonthPayCTE.PayMonth))) = LTRIM(RTRIM(Payroll.month))
 ) AS A  WHERE A.RowNum < 2
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900