AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / dba / Perguntas / 98089
Accepted
Martin F
Martin F
Asked: 2015-04-17 14:01:13 +0800 CST2015-04-17 14:01:13 +0800 CST 2015-04-17 14:01:13 +0800 CST

Como obter o equivalente de funções agregadas de array ou string GROUP BY no Access?

  • 772

Em SQL Aggregate Functions (Office 2007) existem apenas estas GROUP BYfunções agregadas no Access SQL:

Count(), Sum(), Avg(), 
First(), Last(), Min(), Max(), 
StDev(), StDevP(), Var(), VarP()

Das funções agregadas do PostgreSQL existem (entre outras) também estas funções agregadas no PostgreSQL:

array_agg (expression)
  -- input values, including nulls, concatenated into an array

string_agg (expression, delimiter)
  -- input values concatenated into a string, separated by delimiter

Como obter o equivalente GROUP BYa funções agregadas de array ou string no Access? É possível construir funções agregadas do Access SQL? Caso não esteja claro, se eu esses dados

ID col
-----
1  A
1  B
1  C
2  A
3  A
3  B

como posso obter a seguinte agregação?

ID cols
----------
1  A, B, C
2  A
3  A, B

Tenho que recorrer ao VBA? Alguma outra ideia?

Estou usando o Access 2007 - 2010, mas se as coisas forem diferentes em uma versão mais recente, informe-me.

ms-access aggregate
  • 1 1 respostas
  • 14240 Views

1 respostas

  • Voted
  1. Best Answer
    Thomas Cleberg
    2015-04-21T12:54:42+08:002015-04-21T12:54:42+08:00

    O Access vem com um conjunto de funções de agregação de domínio. Uma visão geral deles pode ser encontrada aqui ou na documentação do MSN aqui . Infelizmente, não há nenhuma função de concatenação de domínio nativo.

    Felizmente, Patrick Matthews publicou uma função de concatenação de domínio aqui (e reproduzida abaixo para proteger contra o enfraquecimento do link) que realizará o que você está procurando.

    Da documentação do DConcat():

    SELECT DConcat("Account","Sample") AS Accounts
    FROM Sample
    GROUP BY DConcat("Account","Sample");
    
    
    Returns:
    Accounts
    -----------------------------------------------------------------------------
    Acct1, Acct10, Acct2, Acct3, Acct4, Acct5, Acct6, Acct7, Acct8, Acct9
    

    Para o exemplo específico em questão:

    SELECT ID, DConcat("col","YourTable", "ID=1") AS cols
    FROM YourTable
    WHERE ID=1
    GROUP BY ID, DConcat("col","YourTable", "ID=1")
    

    Deve retornar estes valores:

    ID cols
    ----------
    1  A, B, C
    

    Em seguida, repita para cada IDvalor necessário diferente.

    Function DConcat(ConcatColumns As String, Tbl As String, Optional Criteria As String = "", _
        Optional Delimiter1 As String = ", ", Optional Delimiter2 As String = ", ", _
        Optional Distinct As Boolean = True, Optional Sort As String = "Asc", _
        Optional Limit As Long = 0)
    
        ' Function by Patrick G. Matthews, basically embellishing an approach seen in many
        ' incarnations over the years
    
        ' Requires reference to Microsoft DAO library
    
        ' This function is intended as a "domain aggregate" that concatenates (and delimits) the
        ' various values rather than the more usual Count, Sum, Min, Max, etc.  For example:
        '
        '    Select Field1, DConcat("Field2", "SomeTable", "[Field1] = '" & Field1 & "'") AS List
        '    FROM SomeTable
        '    GROUP BY Field1
        '
        ' will return the distinct values of Field1, along with a concatenated list of all the
        ' distinct Field2 values associated with each Field1 value.
    
        ' ConcatColumns is a comma-delimited list of columns to be concatenated (typically just
        '   one column, but the function accommodates multiple).  Place field names in square
        '   brackets if they do not meet the customary rules for naming DB objects
        ' Tbl is the table/query the data are pulled from.  Place table name in square brackets
        '   if they do not meet the customary rules for naming DB objects
        ' Criteria (optional) are the criteria to be applied in the grouping.  Be sure to use And
        '   or Or as needed to build the right logic, and to encase text values in single quotes
        '   and dates in #
        ' Delimiter1 (optional) is the delimiter used in the concatenation (default is ", ").
        '   Delimiter1 is applied to each row in the code query's result set
        ' Delimiter2 (optional) is the delimiter used in concatenating each column in the result
        '   set if ConcatColumns specifies more than one column (default is ", ")
        ' Distinct (optional) determines whether the distinct values are concatenated (True,
        '   default), or whether all values are concatenated (and thus may get repeated)
        ' Sort (optional) indicates whether the concatenated string is sorted, and if so, if it is
        '   Asc or Desc.  Note that if ConcatColumns has >1 column and you use Desc, only the last
        '   column gets sorted
        ' Limit (optional) places a limit on how many items are placed into the concatenated string.
        '   The Limit argument works as a TOP N qualifier in the SELECT clause
    
        Dim rs As DAO.Recordset
        Dim SQL As String
        Dim ThisItem As String
        Dim FieldCounter As Long
    
        On Error GoTo ErrHandler
    
        ' Initialize to Null
    
        DConcat = Null
    
        ' Build up a query to grab the information needed for the concatenation
    
        SQL = "SELECT " & IIf(Distinct, "DISTINCT ", "") & _
                IIf(Limit > 0, "TOP " & Limit & " ", "") & _
                ConcatColumns & " " & _
            "FROM " & Tbl & " " & _
            IIf(Criteria <> "", "WHERE " & Criteria & " ", "") & _
            Switch(Sort = "Asc", "ORDER BY " & ConcatColumns & " Asc", _
                Sort = "Desc", "ORDER BY " & ConcatColumns & " Desc", True, "")
    
        ' Open the recordset and loop through it:
        ' 1) Concatenate each column in each row of the recordset
        ' 2) Concatenate the resulting concatenated rows in the function's return value
    
        Set rs = CurrentDb.OpenRecordset(SQL)
        With rs
            Do Until .EOF
    
                ' Initialize variable for this row
    
                ThisItem = ""
    
                ' Concatenate columns on this row
    
                For FieldCounter = 0 To rs.Fields.Count - 1
                    ThisItem = ThisItem & Delimiter2 & Nz(rs.Fields(FieldCounter).Value, "")
                Next
    
                ' Trim leading delimiter
    
                ThisItem = Mid(ThisItem, Len(Delimiter2) + 1)
    
                ' Concatenate row result to function return value
    
                DConcat = Nz(DConcat, "") & Delimiter1 & ThisItem
                .MoveNext
            Loop
            .Close
        End With
    
        ' Trim leading delimiter
    
        If Not IsNull(DConcat) Then DConcat = Mid(DConcat, Len(Delimiter1) + 1)
    
        GoTo Cleanup
    
    ErrHandler:
    
        ' Error is most likely an invalid database object name, or bad syntax in the Criteria
    
        DConcat = CVErr(Err.Number)
    
    Cleanup:
        Set rs = Nothing
    
    End Function
    
    • 3

relate perguntas

  • MAX para cada subconjunto

  • Como faço para particionar horizontalmente uma tabela de banco de dados oracle e devo?

  • Usando uma consulta de parâmetro para gerar gráficos em relatórios do MS Access

  • Consultar o banco de dados Linked Access no compartilhamento de rede via SQL Job Agent

  • Calculando a porcentagem de uma linha sobre a soma total

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host

    • 12 respostas
  • Marko Smith

    Como fazer a saída do sqlplus aparecer em uma linha?

    • 3 respostas
  • Marko Smith

    Selecione qual tem data máxima ou data mais recente

    • 3 respostas
  • Marko Smith

    Como faço para listar todos os esquemas no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Listar todas as colunas de uma tabela especificada

    • 5 respostas
  • Marko Smith

    Como usar o sqlplus para se conectar a um banco de dados Oracle localizado em outro host sem modificar meu próprio tnsnames.ora

    • 4 respostas
  • Marko Smith

    Como você mysqldump tabela (s) específica (s)?

    • 4 respostas
  • Marko Smith

    Listar os privilégios do banco de dados usando o psql

    • 10 respostas
  • Marko Smith

    Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Como faço para listar todos os bancos de dados e tabelas usando o psql?

    • 7 respostas
  • Martin Hope
    Jin conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host 2014-12-02 02:54:58 +0800 CST
  • Martin Hope
    Stéphane Como faço para listar todos os esquemas no PostgreSQL? 2013-04-16 11:19:16 +0800 CST
  • Martin Hope
    Mike Walsh Por que o log de transações continua crescendo ou fica sem espaço? 2012-12-05 18:11:22 +0800 CST
  • Martin Hope
    Stephane Rolland Listar todas as colunas de uma tabela especificada 2012-08-14 04:44:44 +0800 CST
  • Martin Hope
    haxney O MySQL pode realizar consultas razoavelmente em bilhões de linhas? 2012-07-03 11:36:13 +0800 CST
  • Martin Hope
    qazwsx Como posso monitorar o andamento de uma importação de um arquivo .sql grande? 2012-05-03 08:54:41 +0800 CST
  • Martin Hope
    markdorison Como você mysqldump tabela (s) específica (s)? 2011-12-17 12:39:37 +0800 CST
  • Martin Hope
    Jonas Como posso cronometrar consultas SQL usando psql? 2011-06-04 02:22:54 +0800 CST
  • Martin Hope
    Jonas Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL? 2011-05-28 00:33:05 +0800 CST
  • Martin Hope
    Jonas Como faço para listar todos os bancos de dados e tabelas usando o psql? 2011-02-18 00:45:49 +0800 CST

Hot tag

sql-server mysql postgresql sql-server-2014 sql-server-2016 oracle sql-server-2008 database-design query-performance sql-server-2017

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve