Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In my database I have data like this

Id | MemberName | CreatedAt |
____________________________
1  | Dhinnaa   | 14-06-2001
2  | senthil   | 11-03-2002
3  | Jhonson   | 22-06-2002
4  | DanielD   | 30-11-2007
5  | Henryee   | 01-01-2008
6  | AnilRex   | 06-07-2008
7  | RexDani   | 01-03-2008


i need to get like this

year1 (1)
year2 (2)
year3 (1)
year4 (3)

How to write query or linq to get this?
Posted
Updated 7-Jul-13 1:48am
v2
Comments
Thanks7872 5-Jul-13 1:29am    
what does year(1),year(2) means?whats the relavance between data and the output?
dineshdena 5-Jul-13 1:44am    
im having the company started at 2001 and i want to calculate the total members who are all added to my company on every year. so 2001,2002,2003 years in want to show like year1,year2,year3 and the count of members at 2001 as year1(count) and 2001 as year2(count)

If you want to do in at the database end follow this.

SQL
declare @tab1 table
(
    id int,
    nam varchar(20),
    cdate  date
)

insert into @tab1 values(1,'Dhinnaa','06/14/2001')
insert into @tab1 values(2,'senthil','06/14/2002')
insert into @tab1 values(3,'Jhonson','06/14/2007')
insert into @tab1 values(4,'DanielD','06/14/2008')
insert into @tab1 values(5,'Henryee','06/14/2002')
insert into @tab1 values(6,'AnilRex','06/14/2008')
insert into @tab1 values(7,'RexDani','06/14/2008')

select  'year(' + cast((ROW_NUMBER() over (order by cyear)) as varchar) + ')',cyear   from
(select count(p.id) idcount,cyear cyear from (
select  id,DATEPART(yy,cdate) as cyear from @tab1) p
group by cyear) q

-- U can try like this also, 

SELECT T.Year, 'Year('+CAST(ROW_NUMBER() OVER(ORDER BY T.Year) AS VARCHAR(5))+')' 'YearCount'
FROM (SELECT YEAR(cdate) 'Year', COUNT(ID) 'RecCount'
	  FROM @tab1 GROUP BY YEAR(cdate)) T
 
Share this answer
 
v2
Try this
C#
foreach(var item in data.GroupBy(x => x.CreatedAt)
                        .Select(group => new {
                             CreatedAt = group.Key,
                             Count = group.Count()
                        })
                        .OrderBy(x => x.CreatedAt)
{
     Console.WriteLine("{0} {1}", item.CreatedAt, item.Count);
}

Hope this helps
 
Share this answer
 
Comments
dineshdena 5-Jul-13 2:36am    
Hello thanq for your reply i find the query for that but i want it in linq will you please help me out thanks in advance.

select year(CreatedAt),count(MemberID) from Members
where ID = 1
group by year(CreatedAt)

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