在MS Access中返回每个组的增量组编号

时间:2018-03-10 00:08:20

标签: ms-access

我需要帮助在Access中创建一个查询,以逐步编号的行组,按公共日期分组,并在下一个日期保持“组编号”增量,如在结果列中显示。

日期| ID |结果

2017/01/09 | 809 | 1

2017/01/09 | 810 | 1

2017/01/09 | 826 | 1

2017/01/10 | 826 | 2

2017/01/11 | 809 | 3

2017/01/11 | 810 | 3

2013/01/11 | 826 | 3

2017/01/12 | 809 | 4

2017/01/12 | 810 | 4

2017/01/12 | 826 | 4

谢谢

2 个答案:

答案 0 :(得分:1)

这是一种方法:
SELECT A.*, (SELECT Count(*) FROM (SELECT DISTINCT [Date] FROM Table1) AS Q1 WHERE A.Date>=[Date]) AS GrpSeq FROM Table1 AS A;

另一个是报告中组头中文本框的属性:
RunningSum:OverGroup
ControlSource:= 1

答案 1 :(得分:0)

您可以使用此功能,这完全是出于此目的。有关典型用法,请参阅内嵌注释:

Public Function RowCounter( _
  ByVal strKey As String, _
  ByVal booReset As Boolean, _
  Optional ByVal strGroupKey As String) _
  As Long

' Builds consecutive RowIDs in select, append or create query
' with the possibility of automatic reset.
' Optionally a grouping key can be passed to reset the row count
' for every group key.
'
' Usage (typical select query):
'   SELECT RowCounter(CStr([ID]),False) AS RowID, *
'   FROM tblSomeTable
'   WHERE (RowCounter(CStr([ID]),False) <> RowCounter("",True));
'
' Usage (with group key):
'   SELECT RowCounter(CStr([ID]),False,CStr[GroupID])) AS RowID, *
'   FROM tblSomeTable
'   WHERE (RowCounter(CStr([ID]),False) <> RowCounter("",True));
'
' The Where statement resets the counter when the query is run
' and is needed for browsing a select query.
'
' Usage (typical append query, manual reset):
' 1. Reset counter manually:
'   Call RowCounter(vbNullString, False)
' 2. Run query:
'   INSERT INTO tblTemp ( RowID )
'   SELECT RowCounter(CStr([ID]),False) AS RowID, *
'   FROM tblSomeTable;
'
' Usage (typical append query, automatic reset):
'   INSERT INTO tblTemp ( RowID )
'   SELECT RowCounter(CStr([ID]),False) AS RowID, *
'   FROM tblSomeTable
'   WHERE (RowCounter("",True)=0);
'
' 2002-04-13. Cactus Data ApS. CPH
' 2002-09-09. Str() sometimes fails. Replaced with CStr().
' 2005-10-21. Str(col.Count + 1) reduced to col.Count + 1.
' 2008-02-27. Optional group parameter added.
' 2010-08-04. Corrected that group key missed first row in group.

  Static col      As New Collection
  Static strGroup As String

  On Error GoTo Err_RowCounter

  If booReset = True Then
    Set col = Nothing
  ElseIf strGroup <> strGroupKey Then
    Set col = Nothing
    strGroup = strGroupKey
    col.Add 1, strKey
  Else
    col.Add col.Count + 1, strKey
  End If

  RowCounter = col(strKey)

Exit_RowCounter:
  Exit Function

Err_RowCounter:
  Select Case Err
    Case 457
      ' Key is present.
      Resume Next
    Case Else
      ' Some other error.
      Resume Exit_RowCounter
  End Select

End Function

对于你的情况,它可能是:

SELECT RowCounter(CStr([ID]), False, Format([Date], "yyyymmdd") AS RowID, *
FROM YourTable
WHERE (RowCounter(CStr([ID]), False) <> RowCounter("", True));