Click here to Skip to main content
15,883,877 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I try this SQL query to get current total and also last 2 months records and current month record means total 3 months..

What I have tried:

SQL
Select distinct tblRv.Owner , 
DATENAME(MONTH,tblRe.StartDate) as [Month],
count(tblvv.VName)
 as currentdata
from tblRe
inner join 
tblRv on tblRe.RID=tblRv.RID
inner join 
 tblvv on tblRv.ID=tblvv.MID
where tblRe.StartDate>=DATEADD(MONTH,-3,GETDATE())
AND tblRe.EndDate<=GETDATE()
AND tblRe.Region='uk'
and tblRv.Owner='roh'
and VName <> ''
group by tblRv.Owner,
DATENAME(MONTH,tblRe.StartDate)
order by tblRv.Owner



this show me data like this
SQL
Owner	Month	currentdata
roh	 July	  3
roh	 June	  10
roh	  May	  6


where as in my table data is like this
SQL
Owner	Month	currentdata
roh	 July	  3
roh	 June	  1
roh	  May	  0


and formatting like thsi i want
SQL
Owner	   july  june may
roh	   3      1     0
Posted
Updated 26-Jul-16 10:02am
v2
Comments
Manoj Kumar Choubey 26-Jul-16 9:26am    
Try with different approach use having
Dil0500 26-Jul-16 9:30am    
You can use pivot
https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx
vani suresh 4-Aug-16 2:44am    
Hi,


Can you post the sample data from the join tables..Let me try for you

1 solution

You want to pivot the result.
Simple Way To Use Pivot In SQL Query[^]
PIVOT and UNPIVOT in Sql Server | SqlHints.com[^]

[Update]
Your question is a double question.
Pivot will do from example 2 to example 3.
You forgot to explain how to change the numbers between example 1 and example 2. Explain the meaning of those numbers.
Use Improve question to update your question.
 
Share this answer
 
v2
Comments
super_user 27-Jul-16 1:14am    
how to use pivot ? will you please describe because i never use this before
Patrice T 27-Jul-16 1:25am    
Are you unable to follow the 2 links in the solution ?
super_user 27-Jul-16 1:29am    
no ok now i get the idea but if use pivot then result is same like this 3,10,6 but i want result like this 3,1,0 . this does not effect on result i think?
Patrice T 27-Jul-16 1:40am    
What is the rule to transform 3.10.6 to 3.1.0 ?
you will certainly have to "prepare" the data before pivot
super_user 27-Jul-16 1:46am    
there is no rule actually when i try to execute query individually like this

select distinct
tblRv.Owner,

count(tblVv.VName) as data
from tblRe
inner join tblRv
on tblRe.RID=tblRv.RID
inner join tblVv
on tblRv.ID=tblVv.MID
where tblRv.Owner='roh' and
tblRe.StartDate = '2016-06-01 00:00:00'
AND tblRe.EndDate <= '2016-06-30 23:59:59'
and VName <> ''
and tblRe.region='uk'
group by
tblRv.Owner,
order by tblRv.Owner

so this show data e.g. in the month of june data is "1"
owner data
roh 1

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