我花了一整天的时间试图找到解决这个问题的方法,但我仍然没有任何线索:
我在一个表用户中有以下字段:
在另一个表 city 两个字段中:
我要做的是从城市中的users_number字段指定的用户表中获取最高行,但首先按分数对获取的行进行排序。用户数量远远大于users_number指定的值。
我的问题是:
是否有可能从表用户中进行选择,其中条件是表城市中的行数?
谢谢
答案 0 :(得分: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
答案 1 :(得分: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