Click here to Skip to main content
15,905,781 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am trying to achive as per my requirement to show task start date falls on in the next 6 months.

I need to show it as forecast report .

select count(*) as [Count], M1 as [Month] from tasktable
where task_startdate between getdate() and dateadd(m,1,getdate())
union all
select count(*) as [Count], M2 as [Month] from tasktable
where task_startdate between dateadd(m,1,getdate()) and dateadd(m,2,getdate())
union all
select count(*) as [Count], M2 as [Month] from tasktable
where task_startdate between dateadd(m,2,getdate()) and dateadd(m,3,getdate()).....etc upto 6 months



output is

countmonth
2m1
5m2
1m3



but i need to make query output as

M1M2M3
251




please help me out to form query...

thanks in advance:)
Posted

Use CASE WNEN... END[^] statemnt.

SQL
SELECT M1, M2, M3, M4, M5, M6
FROM (
    SELECT task_startdate, CASE WHEN task_startdate between getdate() and dateadd(m,1,getdate()) THEN 'M1'
                WHEN task_startdate between dateadd(m,1,getdate()) and dateadd(m,2,getdate()) THEN 'M2'
                WHEN task_startdate between dateadd(m,2,getdate()) and dateadd(m,3,getdate()) THEN 'M3'
                ...
           END AS MyNote
    FROM tasktable
    ) AS DT
PIVOT(COUNT(task_startdate) FOR MyNote IN([M1], [M2], [M3], [M4], [M5], [M6])) AS PVT
 
Share this answer
 
Comments
jvamsikrishna 19-Mar-14 3:09am    
Thanks very much Maciej Los
Maciej Los 19-Mar-14 3:10am    
You're welcome ;)
SQL
select * from tasktable
where task_startdate between getdate() and dateadd(m,1,getdate())
pivot (count (task_startdate) for [Count] in ([M1],[M2],[M3])) as CountOfValues
 
Share this answer
 
learn yourself
Pivot and unpivot
 
Share this answer
 

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