【问题标题】:Fetching variable number of rows from ms access database based on vaules found on another table根据在另一个表上找到的值从 ms access 数据库中获取可变数量的行
【发布时间】:2012-10-16 05:45:54
【问题描述】:

我花了一整天的时间试图想出一个解决这个问题的方法,但我仍然不知道:

我在一个表users中有以下字段:

  • 身份证
  • 姓名
  • city_id
  • 得分

在另一个表city中有两个字段:

  • 身份证
  • users_number

我要做的是从 users 表中获取由 city 中的 users_number 字段指定的前几行,但首先,按分数对获取的行进行排序。用户数量远大于users_number指定的值。

我的问题是:

是否有可能从表 users 中进行选择,其中标准是表 city 中的行数?

谢谢

【问题讨论】:

  • 您已将此标记为 Access 和 Oracle。您是否想提出一个适用于两者的单一查询?为每个优化查询?还是您真的要为一个或另一个数据库标记问题,而不是同时标记两者?
  • 我最初是使用 Access 进行测试的,但由于我认为它是一个困难的查询,因此认为最好在 Oracle 下进行测试,它可能支持更高级的 SQL 功能。所以,无论是 oracle 还是 Access 都可以。

标签: sql ms-access-2007 oracle-xe rownum


【解决方案1】:

这是 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

【讨论】:

    【解决方案2】:

    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
    

    【讨论】:

    • 好吧,我执行了这个查询,但没有令人满意的结果。它不会获取每个城市所需的行数。谢谢。
    猜你喜欢
    • 2016-09-14
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多