MS Access - 如何将增量值添加到表中的组

时间:2014-07-20 18:32:27

标签: sql ms-access

我在MS Access 2007中有一个巨大的项目表出现在产品页面上,看起来与此类似:

ID   | GroupID | ItemName       | Sort | Type

225  | 5       | Specifications | 0    | Text
226  | 5       | Option-Red     | 0    | Product
227  | 5       | Option-Blue    | 0    | Product
228  | 7       | Specifications | 0    | Text
229  | 7       | Option-Green   | 0    | Product
230  | 7       | Option-Orange  | 0    | Product
231  | 7       | Option-Pink    | 0    | Product
232  | 7       | Option-Black   | 0    | Product

每个组中的第一项是规范项,然后是产品列表。

他们需要为每个组添加'sort'序列,以便正在使用的系统将它们按正确的顺序排列,如下所示:

ID   | GroupID | ItemName       | Sort | Type

225  | 5       | Specifications | 0    | Text
226  | 5       | Option-Red     | 1    | Product
227  | 5       | Option-Blue    | 2    | Product
228  | 7       | Specifications | 0    | Text
229  | 7       | Option-Green   | 1    | Product
230  | 7       | Option-Orange  | 2    | Product
231  | 7       | Option-Pink    | 3    | Product
232  | 7       | Option-Black   | 4    | Product

但我似乎无法在访问中创建一个实际上可以执行此操作的查询。有人有任何想法吗?

非常感谢!

2 个答案:

答案 0 :(得分:1)

您应该可以使用以下内容:

select x.id, x.group_id, x.itemname, count(y.id) as sort, x.type
  from tbl x
  left outer join tbl y
    on x.group_id = y.group_id
   and y.id < x.id
 group by x.id, x.group_id, x.itemname, x.type

见小提琴: http://sqlfiddle.com/#!2/bc4e8/3/0

我知道我在那个小提琴中使用了mysql,但我没有使用Access不支持的任何语法,我不相信。您可能要做的唯一事情就是在()中包含on子句,我忘记了on子​​句如何与Access一起使用但是知道它很奇怪。

答案 1 :(得分:0)

更新评论: 您可以使用:

 Select * from (
 Select * from yourTableName ORDER BY yourTableName.Sort)
 ORDER BY yourTableName.GroupID

创建简单查询时,请转到SQL模式并插入代码。