sql server - SQL for filter records based on another query on the same table -


i have table following columns

  1. trialid
  2. points
  3. trialdatetime
  4. userid

this represents trials done user & points scored in trial. particular user may 10 trials may have 10 records in table.

i want records points greated 50, if trial represents 4th or more trial of particular user. number of particular trial not represented in table. however, if userid has 5 trials, datetime field can used figure out first/second etc.

so want trials score greater 50 & same userid has 3 other other trials in table has lesser datetime.

is there way via sql?

i know can get

select * tbl points > 50; 

will me records points > 50, how filter further?

if had datetime of particular record in variable called x, do

select count(trialid) tbl trialdatetime > 'somedatetime' , userid = 'someuid'. 

to check if there more 3 older records same userid. there way combine both of using sql? other options have?

sample records

1. t1, 20, 2013-05-09 14:10:27.000, u1 2. t2, 40, 2013-05-09 14:20:27.000, u1 3. t3, 45, 2013-05-09 14:30:27.000, u1 4. t4, 60, 2013-05-09 14:40:27.000, u1 5. t5, 20, 2013-05-09 12:11:27.000, u2 6. t6, 30, 2013-05-09 12:12:27.000, u2 7. t7, 60, 2013-05-09 12:13:27.000, u2 8. t8, 40, 2013-05-09 12:54:27.000, u2 

here record 4 selected. however, record 7 not selected though both have scores above 50.

using sql server 2008 r2.

maybe this:

;with cte (     select          row_number() over(partition t.userid                            order t.trialdatetime) nbroftrails,         t.*              tbl t ) select     *     cte     cte.nbroftrails > 3     , cte.points > 50 

references:

using common table expressions

row_number (transact-sql)


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -