пользовательский смешанный запрос листинга в SQL - PullRequest
0 голосов
/ 20 июня 2019

предположим, что У меня есть БД, который включен в поле USR_NR (целочисленный тип). и я знаю все данные в поле. никаких сюрпризов №.

USR_NR : 1,3,4,7,9,12,44,13,78

Мне нужно перечислить это поле как смешанное, как 1,78,44,9,7,3,12,4,13 нет правил для листинга. Я хочу отсортировать, как я хотел.

Я пробовал с ORDER BY, но как мне продвинуться? Я не могу использовать ASC, DESC

SELECT * FROM DB ORDER BY ?

Не могли бы вы помочь мне в этом?

Ответы [ 2 ]

1 голос
/ 20 июня 2019

Вы можете использовать instr():

order by instr(",1,78,44,9,7,3,12,4,13,", "," & USR_NR & ",")

Или, несколько более подробно, использовать switch:

order by switch(USR_NR = 1,  1,
                USR_NR = 78, 2,
                USR_NR = 44, 3,
                . . .
               )
1 голос
/ 20 июня 2019

Вам нужна форма, в которой вы можете установить номер приоритета для каждой записи, используя такую ​​функцию:

' Set the priority order of a record relative to the other records of a form.
'
' The table/query bound to the form must have an updatable numeric field for
' storing the priority of the record. Default value of this should be Null.
'
' Requires:
'   A numeric, primary key, typical an AutoNumber field.
'
' 2018-08-31. Gustav Brock, Cactus Data ApS, CPH.
'
Public Sub RowPriority( _
    ByRef TextBox As Access.TextBox, _
    Optional ByVal IdControlName As String = "Id")

    ' Error codes.
    ' This action is not supported in transactions.
    Const NotSupported      As Long = 3246
    Dim Form                As Access.Form
    Dim Records             As DAO.Recordset

    Dim RecordId            As Long
    Dim NewPriority         As Long
    Dim PriorityFix         As Long
    Dim FieldName           As String
    Dim IdFieldName         As String

    Dim Prompt              As String
    Dim Buttons             As VbMsgBoxStyle
    Dim Title               As String

    On Error GoTo Err_RowPriority

    Set Form = TextBox.Parent

    If Form.NewRecord Then
        ' Will happen if the last record of the form is deleted.
        Exit Sub
    Else
        ' Save record.
        Form.Dirty = False
    End If

    ' Priority control can have any Name.
    FieldName = TextBox.ControlSource
    ' Id (primary key) control can have any name.
    IdFieldName = Form.Controls(IdControlName).ControlSource

    ' Prepare form.
    DoCmd.Hourglass True
    Form.Repaint
    Form.Painting = False

    ' Current Id and priority.
    RecordId = Form.Controls(IdControlName).Value
    PriorityFix = Nz(TextBox.Value, 0)
    If PriorityFix <= 0 Then
        PriorityFix = 1
        TextBox.Value = PriorityFix
        Form.Dirty = False
    End If

    ' Disable a filter.
    ' If a filter is applied, only the filtered records
    ' will be reordered, and duplicates might be created.
    Form.FilterOn = False

    ' Rebuild priority list.
    Set Records = Form.RecordsetClone
    Records.MoveFirst
    While Not Records.EOF
        If Records.Fields(IdFieldName).Value <> RecordId Then
            NewPriority = NewPriority + 1
            If NewPriority = PriorityFix Then
                ' Move this record to next lower priority.
                NewPriority = NewPriority + 1
            End If
            If Nz(Records.Fields(FieldName).Value, 0) = NewPriority Then
                ' Priority hasn't changed for this record.
            Else
                ' Assign new priority.
                Records.Edit
                    Records.Fields(FieldName).Value = NewPriority
                Records.Update
            End If
        End If
        Records.MoveNext
    Wend

    ' Reorder form and relocate record position.
    ' Will fail if more than one record is pasted in.
    Form.Requery
    Set Records = Form.RecordsetClone
    Records.FindFirst "[" & IdFieldName & "] = " & RecordId & ""
    Form.Bookmark = Records.Bookmark

PreExit_RowPriority:
    ' Enable a filter.
    Form.FilterOn = True
    ' Present form.
    Form.Painting = True
    DoCmd.Hourglass False

    Set Records = Nothing
    Set Form = Nothing

Exit_RowPriority:
    Exit Sub

Err_RowPriority:
    Select Case Err.Number
        Case NotSupported
            ' Will happen if more than one record is pasted in.
            Resume PreExit_RowPriority
        Case Else
            ' Unexpected error.
            Prompt = "Error " & Err.Number & ": " & Err.Description
            Buttons = vbCritical + vbOKOnly
            Title = Form.Name
            MsgBox Prompt, Buttons, Title

            ' Restore form.
            Form.Painting = True
            DoCmd.Hourglass False
            Resume Exit_RowPriority
    End Select

End Sub

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

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

Если у вас нет учетной записи, перейдите по ссылке: Прочитайте статью полностью.

Код также включен GitHub : VBA.RowNumbers

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