Добавление последовательного индекса в таблицу, упорядоченную по трем полям - PullRequest
0 голосов
/ 19 апреля 2019

У меня есть таблица a с полями aA, aB, aC

Я пытаюсь создать таблицу b с полями bA, bB, bC, bD с запросом:

SELECT a.A, a.B, a.C, 
(Sequential integers from first record returned to last record returned) AS D 
into b
FROM a WHERE a.C is not null
ORDER BY a.C, a.B DESC, a.A;

Примервывод таблицы b:

A, B, C, D
9500, 106.12, 9507, 1
9507, 106.12, 9516, 2
9485, 106.11, 9516, 3
9472, 106.1, 9516, 4
9432, 106.09, 9516, 5
9528, 106.14, 9531, 6
9523, 106.13, 9536, 7
9531, 106.14, 9540, 8
9540, 106.14, 9545, 9
9545, 106.14, 9548, 10
9548, 106.14, 9555, 11
9570, 106.21, 9572, 12
9575, 106.22, 9580, 13
9580, 106.22, 9583, 14

A является уникальным идентификатором.

Это будет выполняться в таблице с миллионами записей.

Моя задача с (Последовательное возрастаниецелые числа из первой записи, возвращенной к последней записи, возвращенной).Кто-нибудь есть предложение о том, что поставить в скобках, которые помогут мне создать таблицу б, используя только запрос?

Ответы [ 2 ]

1 голос
/ 19 апреля 2019

Вы можете использовать мою функцию RowNumber :

' Builds consecutive row numbers in a select, append, or create query
' with the option of a initial automatic reset.
' Optionally, a grouping key can be passed to reset the row count
' for every group key.
'
' 2018-08-23. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function RowNumber( _
    ByVal Key As String, _
    Optional ByVal GroupKey As String, _
    Optional ByVal Reset As Boolean) _
    As Long

    ' Uncommon character string to assemble GroupKey and Key as a compound key.
    Const KeySeparator      As String = "¤§¤"
    ' Expected error codes to accept.
    Const CannotAddKey      As Long = 457
    Const CannotRemoveKey   As Long = 5

    Static Keys             As New Collection
    Static GroupKeys        As New Collection
    Dim Count               As Long
    Dim CompoundKey         As String

    On Error GoTo Err_RowNumber

    If Reset = True Then
        ' Erase the collection of keys and group key counts.
        Set Keys = Nothing
        Set GroupKeys = Nothing
    Else
        ' Create a compound key to uniquely identify GroupKey and its Key.
        ' Note: If GroupKey is not used, only one element will be added.
        CompoundKey = GroupKey & KeySeparator & Key
        Count = Keys(CompoundKey)

        If Count = 0 Then
            ' This record has not been enumerated.
            '
            ' Will either fail if the group key is new, leaving Count as zero,
            ' or retrieve the count of already enumerated records with this group key.
            Count = GroupKeys(GroupKey) + 1
            If Count > 0 Then
                ' The group key has been recorded.
                ' Remove it to allow it to be recreated holding the new count.
                GroupKeys.Remove (GroupKey)
            Else
                ' This record is the first having this group key.
                ' Thus, the count is 1.
                Count = 1
            End If
            ' (Re)create the group key item with the value of the count of keys.
            GroupKeys.Add Count, GroupKey
        End If
        ' Add the key and its enumeration.
        ' This will be:
        '   Using no group key: Relative to the full recordset.
        '   Using a group key:  Relative to the group key.
        ' Will fail if the key already has been created.
        Keys.Add Count, CompoundKey
    End If

    ' Return the key value as this is the row counter.
    RowNumber = Count

Exit_RowNumber:
    Exit Function

Err_RowNumber:
    Select Case Err
        Case CannotAddKey
            ' Key is present, thus cannot be added again.
            Resume Next
        Case CannotRemoveKey
            ' GroupKey is not present, thus cannot be removed.
            Resume Next
        Case Else
            ' Some other error. Ignore.
            Resume Exit_RowNumber
    End Select

End Function

и запрос на добавление, подобный этому:

INSERT INTO TempTable ( [RowID] )
SELECT RowNumber(CStr([ID])) AS RowID, *
FROM SomeTable
WHERE (RowNumber("","",True)=0);

Полное описание, включая демонстрацию, можно найти здесь:

Последовательные строки в Microsoft Access

и на GitHub: VBA.RowNumbers

1 голос
/ 19 апреля 2019

Я думаю, что самый простой способ - сначала определить новую таблицу и использовать insert:

create table b (
    b_id autoincrement primary key,
    a ?,  -- ? is for the type of the column
    b ?,
    c ?
);

insert into b (a, b, c)
    select a.A, a.B, a.C, 
    from a 
    where a.C is not null
    orer by a.C, a.B desc, a.A;

MS Access не имеет удобной функции, такой как row_number() (поддерживается почти всеми другими базами данных), чтобы сделать это проще.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...