0

I have a table with below data.

table name: t_keyword_count

f_id       f_keyword      f_count      f_dominant
==================================================
101        C++              2               0
101        Java             4               0
101        PHP              6               0
101        Python           5               0
101        Ruby             9               0
102        ruby             4               0
102        java             6               0
102        php              9               0
102        C++              7               0
102        Jquery           2               0

Like that


My Requirment is: I need update f_dominant status as 1 where I want top 3 f_count values with respect to f_id . i.e I want this result set

 101  ruby     9  1
 101  php      6  1
 101  python   5  1
 101  JAVA     4  0
 101  c++      2  0
 102  php      9  1
 102  c++      7  1
 102  jAVA     6  1
 102  RUBY     4  0
 102  JQUERY   2  0
4

2 回答 2

1
SELECT x.*
     , CASE WHEN COUNT(*) <= 3 THEN 1 ELSE 0 END f_dominant
  FROM t_keyword_count x
  JOIN t_keyword_count y 
    ON y.f_id = x.f_id 
   AND y.f_count >= x.f_count 
 GROUP 
    BY x.f_id,x.f_keyword
 ORDER 
    BY f_id,f_count DESC;

或类似的东西

于 2013-10-21T12:43:12.853 回答
0

这可行,但如果行太多,它可能会很慢:

update t_keyword_count t
  set f_dominant =
    f_count >= ( select f_count from
                   ( select * from t_keyword_count ) a 
                   where f_id = t.f_id
                 order by f_count desc
                 limit 2,1
               )

http://sqlfiddle.com/#!2/47504/2

或者如果只更新一次:

update t_keyword_count t
  set f_dominant = 1
  where f_count >= ( select f_count from
                   ( select * from t_keyword_count ) a 
                   where f_id = t.f_id
                 order by f_count desc
                 limit 2,1
               )

http://sqlfiddle.com/#!2/de3ec/1

于 2013-10-21T13:17:11.000 回答