Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 SQL group by with Year() function

Author  Topic 

madhan
Yak Posting Veteran

59 Posts

Posted - 2014-06-19 : 12:38:08
[code]
select empid,orderdate from [Sales].[Orders] WHERE custid = 71
group by empid,orderdate
[/code]

sample data resultset:
empid orderdate
1 2006-12-25
1 2007-12-24
1 2007-12-23
1 2008-12-23
1 2008-04-24



[code]
select empid,year(orderdate) from [Sales].[Orders] WHERE custid = 71
group by empid,year(orderdate)

[/code]

sample data resultset:
empid orderdate
1 2006
1 2007
1 2008

why is the year() gets only one year when worked with groupby. when empid =1 the year 2007 has 2 records and 2008 has 2 records in first select and when I used year(orderdate) in secong select only one year for each is selected. I don't understand why is this happening. Please help me understand this....

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2014-06-19 : 13:05:46
It's "aggregating" the data. If you add COUNT(*) as one of the columns, you will see that SQL is aggregating 2 rows into one based on your GROUP BY clause.
Go to Top of Page

gbritton
Master Smack Fu Yak Hacker

2780 Posts

Posted - 2014-06-19 : 13:07:28
You're only projecting the groups (empid, year(orderdate)) and the results are correct. Did you want to count the records per year instead?

e.g.


select count(*) empids, year(orderdate) 'year' from [Sales].[Orders] WHERE custid = 71
group by year(orderdate)
Go to Top of Page

madhan
Yak Posting Veteran

59 Posts

Posted - 2014-06-19 : 14:28:09
Thanks for the help, I understood.
Go to Top of Page
   

- Advertisement -