How to query this? [modified]
-
The table consists of 3 columns: ID,Date,Value. Sample Data:
ID Date Value
1 1/1/2004 243
2 1/1/2004 0
3 1/1/2004 324231 2/1/2004 2435
2 2/1/2004 545
3 2/1/2004 0The above table holds transactions for last 3 months for each ID(from 1 to 1000). It will have records till yesterday. I need a query that return 5 rows for each ID having value >0. The result might look like: for ID=1:last 5 dates where value>0 for ID=2:last 5 dates where value>0 and so on. Thanks in advance. Or atleast is there any way to find the 2nd maximum along with group by. Or atleast is there any way to combine "top" along with group by. -- modified at 12:26 Saturday 19th May, 2007
Regards, Arun Kumar.A
-
The table consists of 3 columns: ID,Date,Value. Sample Data:
ID Date Value
1 1/1/2004 243
2 1/1/2004 0
3 1/1/2004 324231 2/1/2004 2435
2 2/1/2004 545
3 2/1/2004 0The above table holds transactions for last 3 months for each ID(from 1 to 1000). It will have records till yesterday. I need a query that return 5 rows for each ID having value >0. The result might look like: for ID=1:last 5 dates where value>0 for ID=2:last 5 dates where value>0 and so on. Thanks in advance. Or atleast is there any way to find the 2nd maximum along with group by. Or atleast is there any way to combine "top" along with group by. -- modified at 12:26 Saturday 19th May, 2007
Regards, Arun Kumar.A
IMO, you can use GROUP BY...HAVING...you can get more info from SQL online book << >>
-
IMO, you can use GROUP BY...HAVING...you can get more info from SQL online book << >>
Thank you very much for your reply... But still I am not able to find the exact answer.
Regards, Arun Kumar.A
-
Thank you very much for your reply... But still I am not able to find the exact answer.
Regards, Arun Kumar.A
What have you tried so far? try this...
SELECT ... FROM...GROUP BY ID HAVING value > 0
<< >> -
What have you tried so far? try this...
SELECT ... FROM...GROUP BY ID HAVING value > 0
<< >> -
the best soultion is create a cursor and put cursor in stored procedure(SP) , finally call SP ------------------------------- declare @vdd bigint declare C1 cursor for Select distinct id from pdata open C1 drop table #temsales CREATE TABLE #temsales ( col1 bigint, col2 datetime, col3 bigint ) fetch next from c1 into @vdd while @@fetch_status=0 begin insert into #temsales select top 5 * from pdata where sales>0 and id =@vdd fetch next from c1 into @vdd end close c1 deallocate c1 select * from #temsales ;)