1

この問題の解決策を考え出すために一日中費やしましたが、まだ手がかりがありません:

私は1つのテーブルユーザーに次のフィールドを持っています:

  • ID
  • 名前
  • city_id
  • スコア

そして、別のテーブルcityには2 つのフィールドがあります。

  • ID
  • ユーザー数

私がしなければならないことは、city の users_number フィールドで指定されているように users テーブルから一番上の行を取得することですが最初、フェッチされた行をスコアで並べ替えます。ユーザー数が users_number で指定された値をはるかに超えています。

私の質問は:

基準がテーブル都市の行数であるテーブルユーザーから選択する可能性はありますか?

ありがとうございました

4

2 に答える 2

0

MS Accessの場合はどうですか:

SELECT t.ID, (
   SELECT Count(ID) 
   FROM users s 
   WHERE s.ID<=t.ID And s.city_id=t.city_id) AS Expr1
FROM users AS t
INNER JOIN City c
ON t.city_id = c.ID
WHERE (
    SELECT Count(ID) 
    FROM users s 
    WHERE s.ID<=t.ID And s.city_id=t.city_id)<=c.users_number
ORDER BY t.ID

結果:

id  city_id Expr1
1       1       1
2       1       2 
-----------------------------
5       2       1
6       2       2
7       2       3
-----------------------------
9       3       1

ID はユーザー ID で、Expr1 はオーダーです。

入力

ユーザー

id  name    city_id 
1   a       1   
2   b       1   
3   c       1   
4   d       1   
5   e       2   
6   a       2   
7   b       2   
8   c       2   
9   d       3   
10  e       3

id  users_number
1   2
2   3
3   1
于 2012-10-25T23:34:24.763 に答える
0

T-SQL の回答は、Access でそれを理解するのに役立つでしょうか?

declare @users table 
(
    id int primary key clustered
    , name nvarchar(64)
    , city_id int 
    , score int
)
declare @city table (
    id int primary key clustered
    , name nvarchar(64)
    , users_number int
)

insert @city
      select 1, 'San Fran', 2
union select 2, 'NY', 5

insert @users
      select 1, 'Steve Fields', 1, 10
union select 2, 'Sarah Felcher', 1, 20
union select 3, 'Nick Yarnton', 2, 12
union select 4, 'Nigel Yardsman', 2, 12
union select 5, 'Nicki Yakatou', 2, 13
union select 6, 'Nicola Yates', 2, 23
union select 7, 'Steph Freeman', 1, 15
union select 8, 'Ned Yount', 2, 18
union select 9, 'Neil Yorke', 2, 1

select *
from @city c
left outer join 
(
    select id, name, city_id, score
    , ROW_NUMBER() over (partition by city_id order by score desc) r
    from @users
) u
on c.id = u.city_id
where c.users_number >= u.r
order by c.id, u.score desc
于 2012-10-25T23:43:38.660 に答える