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
 Ranking Dates

Author  Topic 

shoham
Starting Member

6 Posts

Posted - 2012-09-19 : 04:58:05
Hello
I have an orders table with USER_ID and ORDER_DATE
I want to achieve somthing like this:
SELECT [USER_ID], [FIRST_ORDER_DATE], [SECOND_ORDER_DATE], [THIRD_ORDER_DATE], [FOURTH_ORDER_DATE]
FROM ORDERS

I have tried to create a scalar function (getFirstOrder, getSecondOrder, ...)
but after the third its very slow

any ideas?

Thanks!

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2012-09-19 : 05:12:17
[code]SELECT [USER_ID],
[1] as [FIRST_ORDER_DATE],
[2] as [SECOND_ORDER_DATE],
[3] as [THIRD_ORDER_DATE],
[4] as [FOURTH_ORDER_DATE]
FROM (
SELECT [USER_ID],
[ORDER_DATE],
RN = row_number() over (partition by [USER_ID] order by [ORDER_DATE])
FROM ORDERS
) D
PIVOT (
MAX(ORDER_DATE)
FOR RN in ([1], [2], [3], [4])
) P[/code]


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

shoham
Starting Member

6 Posts

Posted - 2012-09-19 : 05:54:44
Thanks! thats great!!
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-09-19 : 11:55:01
you can always extend it like below in case you need to show variable number of dates

http://beyondrelational.com/modules/2/blogs/70/posts/10840/dynamic-pivot-in-sql-server-2005.aspx

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -