Contido

# Funcións de base de datos

### Visión xeral

As doce funcións da categoría Base de datos axudan a analizar unha base de datos sinxela que ocupa unha área rectangular da folla de cálculo composta de columnas e filas, cos datos organizados como unha fila para cada rexistro. A cela de cabeceira de cada columna mostra o nome da columna e ese nome habitualmente reflicte o contido de cada cela desa columna.

As funcións da categoría Base de datos acepta tres argumentos, os seguintes:

1. Base de datos. O intervalo de celas da base de datos.

2. CampoBaseDeDatos. A columna que contén os datos para empregar nos cálculos da función.

3. CriteriosDeBusca. O intervalo de celas dunha área separada da folla de cálculo que contén os criterios de busca.

Estes argumentos descríbense polo miúdo máis abaixo.

Todas as funcións teñen o mesmo concepto básico de funcionamento. O primeiro paso lóxico é empregar os CriteriosDeBusca para identificar o subconxunto de rexistros da BaseDeDatos que se van empregar durante os cálculos subsecuentes. O segundo paso consiste en extraer os valores dos datos e realizar os cálculos asociados coa función indicada (media, suma, produto, etc.). Os valores procesados son os da columna CampoDaBaseDeDatosdos rexistros seleccionados.

O Calc trata as datas e os valores lóxicos (VERDADEIRO e FALSO) como numéricos ao calcular con estas funcións.

### Argumentos das funcións de base de datos

As definicións dos argumentos seguintes aplícanselles a todas as funcións da categoría Base de datos:

1. Argumento BaseDeDatos

   BaseDeDatos indica o intervalo de celas ocupado pola táboa da base de datos. A primeira fila do intervalo contén os nomes dos campos e as filas posteriores son rexistros cos valores de campo correspondentes.

   Unha maneira de definir o intervalo de celas é introducir a referencia de cela da cela superior esquerda seguinda de dous puntos (:) seguida da referncia da cela inferior dereita. Un exemplo podería ser A1:E10.

   O argumento BaseDeDatos tamén se pode indicar pasando o nome dun intervalo nomeado ou dun intervalo da base de datos. O emprego dun nome significativo para definir o intervalo de celas pode mellorar a lexibilidade da fórmula e o mantemento do documento. Se o nome non coincide co nome dun intervalo definido, o Cal informa dun erro #NOME?.

   Outros erros dos que pode informar como resultado dun argumento BaseDeDatos incorrecto son #VALOR e Err:504 (erro na lista de parámetros).

2. Argumento CampoBaseDeDatos

   CampoBaseDeDatos indica a columna que vai empregar a función para os seus cálculos unha vez aplicados os criterios de busca e seleccionadas as filas de datos. Non está relacionado cos criterios de busca.

   Indique o argumento CampoBaseDeDatos de calquera das maneiras seguintes:

   - Introducindo unha referencia a unha cela de cabeceira na área BaseDeDatos. Como alternativa, se a cela recibiu un nome significativo, como un intervalo nomeado ou un intervalo de base de datos, introduza ese nome. Se o nome non coincide co nome ou cun intervalo definido, o Calc informa dun erro #NAME?. Se o nome for válido mais non corresponder a unha única cela, o Calc informa do erro Err:504 (erro na lista de parámetros).

   - Ao introducir un número para especificar a columna na área Base de datos, comezando por 1. Por exemplo, se unha Base de datos ocupou o intervalo de celas D6:H123, introduza 3 para indicar a cela de cabeceira en F6. Calc espera un valor enteiro entre 1 e o número de columnas definido en Base de datos e ignora calquera díxito que siga a vírgula decimal. Se o valor é menor de 1, Calc informa dun erro Err:504 (erro na lista de parámetros). Se o valor for maior do número de columnas en Base de datos, Calc informa dun erro #VALOR!.

   - Ao introducir o nome literal da cabeceira da columna da primeira fila do intervalo da Base de datos, colocando aspas arredor do nome da cabeceira. Por exemplo, «Distancia até a escola». Se a cadea non corresponde cunha cas cabeceiras da columna da área Base de datos, o Calc informa dun erro Err:504 (erro na lista de parámetros). Tamén pode fornecer unha referencia a unha cela arbitraria (fóra das áreas de Base de datos e Criterio de busca) que conteña a cadea requirida.

   O argumento CampoDeBaseDeDatos é opcional para as funcións BDCONTAR e BDCONTARA mais obrigatorio para as dez funcións de bases de datos restantes.

3. Argumento CriteriosBusca

   SearchCriteria specifies the range of cells containing search criteria. Like Database, its first row is also field names, and subsequent rows are conditions for related fields. The Database and SearchCriteria areas need not be adjacent, or even on the same sheet.

   Unha maneira de definir o intervalo de celas é introducir a referencia da cela superior esquerda seguida de dous puntos (:) e despois a referencia da cela inferior dereita. Por exemplo, A13:B14. Tamén se pode indicar o intervalo de celas pasando o nome dun intervalo con nome definido ou dun intervalo de base de datos. Se o nome non corresponde co nome dun intervalo definido, Calc informa dun erro #NOME?.

   Err:504 (error in parameter list) may also be reported as a result of an invalid SearchCriteria argument.

   The contents of the SearchCriteria area are described in more detail in the next section.

### Definir criterios de busca

The number of columns occupied by the SearchCriteria area need not be the same as the width of the Database area. All headings that appear in the first row of SearchCriteria must be identical to headings in the first row of Database. However, not all headings in Database need appear in the first row of SearchCriteria, while a heading in Database can appear multiple times in the first row of SearchCriteria.

Search criteria are entered into the cells of the second and subsequent rows of the SearchCriteria area, below the row containing headings. Blank cells within the SearchCriteria area are ignored.

Cree criterios nas celas da área CriterioBusca empregando os operadores de comparación <, <=, =, <>, >=, and >. Asúmese = se unha cela non está baleira mais non comeza cun operador de comparación.

Se escribe varios criterios nunha fila, estes conéctanse con E. Se escribe varios criterios en filas diferentes, conéctanse con OU.

Pódense crear criterios empregando comodíns sempre que os comodíns fosen activados mediante a opción Activar comodíns en fórmulas da caixa de diálogoLibreOffice - Preferencias Ferramentas - Opcións - Calc do LibreOffice - Calcular. Esta opción debería estar activada se a interoperabilidade co Excel da Microsoft for importante para a folla de cálculo.

Pódense crear criterios máis potentes empregando expresións regulares, sempre que as expresións regulares estivesen activadas mediante a opción Activar expresións regulares nas fórmulas na caixa de diálogo LibreOffice - Preferencias Ferramentas - Opcións - Calc do LibreOffice - Calcular

Ao empregar funcións nas que un ou máis argumentos sexan criterios de busca que representen unha expresión regular, téntase primeiro converter os criterios da cadea en números. Por exemplo, «.0» convértese en 0.0, etc. Se resulta ben, a busca non será unha coincidencia de expresión regular senón unha coincidencia numérica. Porén, ao traballar cunha configuración rexional na que o separador decimal non sexa o punto, como en galego, o punto fai que funcione a conversión a expresión regular. Para obrigar a que a avaliación sexa dunha expresión regular no canto dunha expresión numérica hai que empregar algunha expresión que non se poda confundir cunha numérica, como «.[0]», «.\0» ou «(?i).0».

Another setting that affects how the search criteria are handled is the Search criteria = and <> must apply to whole cells option on the LibreOffice - Preferences Tools - Options - LibreOffice Calc - Calculate dialog. This option controls whether the search criteria you set for the Database functions must match the whole cell exactly. When interoperability with Microsoft Excel is important for your spreadsheet, this option should be enabled.

### Exemplos de uso das funcións de base de datos

A táboa seguinte fornece unha táboa de base de datos de exemplo que se emprega para demostrar como usar as funcións da categoría Base de datos. O intervalo de celas A1:E10 contén información ficticia sobre os convidados á festa de aniversario de Joe. Para cada convidado dáse a información seguinte - nome, curso, idade en anos, distancia á escola en metros e peso en quilogramos.

| A | B | C | D | E
1 | Nome | Curso | Idade | Distancia | Peso
2 | André | 3 | 9 | 150 | 40
3 | Bea | 4 | 10 | 1000 | 42
4 | Carlos | 3 | 10 | 300 | 51
5 | Daniel | 5 | 11 | 1200 | 48
6 | Eva | 2 | 8 | 650 | 33
7 | Francisco | 2 | 7 | 300 | 42
8 | Greta | 1 | 7 | 200 | 36
9 | Henrique | 3 | 9 | 1200 | 44
10 | Irene | 2 | 8 | 1000 | 42
11 |  |  |  |  |

Os seis exemplos a seguir empregan a táboa de base de datos anterior combinada con diferentes áreas de criterios de busca.

#### Exemplo 1

| A | B | C | D | E
12 | Nome | Curso | Idade | Distancia | Peso
13 |  |  |  | >600 |
14 |  |  |  |  |

Como neste exemplo sinxelo, ás veces é desexábel (aínda que non esencial) colocar a área de criterios de busca directamente baixo a táboa da base de datos, coas columnas das dúas áreas aliñadas verticalmente. Ignóranse as entradas baleiras da área de criterios de busca. Coa táboa de base de datos do exemplo anterior e esta área de criterios de busca, insira a fórmula =DCOUNT(A1:E10;;A12:E14) nunha cela baleira doutra parte da folla para contar o número de convidados de Joe que viaxan máis de 600 metros até a escola. Retorna o valor de 5 (contando a Betty, Daniel, Eva, Harry e Irene).

Note also that the formula =DCOUNT(A1:E10;;D12:D13) returns exactly the same value, demonstrating that it is only necessary for the search criteria area to contain relevant column headings.

#### Example 2

| A | B | C | D | E
12 |  | Age | Grade |  |
13 |  | >7 | 2 |  |
14 |  |  |  |  |

In this example the search criteria area contains only two headings and these are not vertically aligned with the corresponding headings in the example database table. Since there are two conditions in the same row, these are connected by AND. With the above example database table and this search criteria area, insert the formula =DCOUNT(A1:E10;;B12:C13) into an empty cell elsewhere in the sheet to count how many of Joe’s guests are in grade 2 and greater than 7 years old. The value 2 is returned (counting Eva and Irene).

#### Example 3

| A | B | C | D | E
12 |  | Age |  |  |
13 |  | 9 |  |  |
14 |  | 10 |  |  |

In this example the search criteria area contains only one heading. Since there are two conditions in consecutive rows, these are connected by OR. With the above example database table and this search criteria area, insert the formula =DCOUNT(A1:E10;;B12:B14) into an empty cell elsewhere in the sheet to count how many of Joe’s guests are either 9 or 10 years old. The value 4 is returned (counting Andy, Betty, Charles, and Harry).

#### Example 4

| A | B | C | D | E
12 |  | Age | Age |  |
13 |  | >=8 | <=10 |  |
14 |  |  |  |  |

In this example the search criteria area contains two occurrences of the same heading. Since there are two conditions in the same row, these are connected by AND. With the above example database table and this search criteria area, insert the formula =DCOUNT(A1:E10;;B12:C13) into an empty cell elsewhere in the sheet to count how many of Joe’s guests are aged between 8 and 10 (inclusive). The value 6 is returned (counting Andy, Betty, Charles, Eva, Harry, and Irene).

#### Example 5

| A | B | C | D | E
12 | Nome |  |  |  |
13 | F* |  |  |  |
14 |  |  |  |  |

This simple example shows the use of wildcards. For this example to work as intended, select to enable wildcards at LibreOffice - Preferences Tools - Options - LibreOffice Calc - Calculate. With the above example database table and this search criteria area, insert the formula =DCOUNT(A1:E10;;A12:A13) into an empty cell elsewhere in the sheet to count how many of Joe’s guests have names that begin with the letter “F”. The value 1 is returned (counting Frank).

#### Example 6

| A | B | C | D | E
12 | Nome |  |  |  |
13 | [ABC].* |  |  |  |
14 |  |  |  |  |

This simple example shows the use of regular expressions. For this example to work as intended, select to enable regular expressions at LibreOffice - Preferences Tools - Options - LibreOffice Calc - Calculate. With the above example database table and this search criteria area, insert the formula =DCOUNT(A1:E10;;A12:A13) into an empty cell elsewhere in the sheet to count how many of Joe’s guests have names that begin with the letters “A”, “B”, or “C”. The value 3 is returned (counting Andy, Betty, and Charles).

## BDCONTAR

DCOUNT counts the number of cells (fields) of the specified column that contain numeric values, for all rows (database records) that match the specified search criteria. However, if no column is specified, DCOUNT returns the count of all records that match the specified search criteria irrespective of their contents.

#### Sintaxe

DCOUNT (Base de Datos; DatabaseField; campo de busca)

#### Exemplo

The example database table giving information about the guests invited to Joe’s birthday party (described above) should occupy cells A1:E10. The content of cells A12:E12 should be identical to the header labels for the database table in cells A1:E1. Make sure that cells A13:E13 are blank, except for cell D13 which should contain ">600" (this search criterion will match records in the database table that have a value greater than 600 in the Distance column).

Insert the formula =DCOUNT(A1:E10;; A12:E13) into an empty cell elsewhere in the sheet to calculate how many of Joe’s party guests travel further than 600 meters to school. The value 5 is returned.

The same result is obtained if you use the formula =DCOUNT(A1:E10; "Distance"; A12:E13), because all entries in the Distance column are numeric. However, if you use the formula =DCOUNT(A1:E10; "Name"; A12:E13), the value 0 is returned because all entries in the Name column are non-numeric.

## BDCONTARA

DCOUNTA counts the number of cells (fields) of the specified column that are not blank, for all rows (database records) that match the specified search criteria. Blank cells of the specified column are not counted. However, if no column is specified, DCOUNTA returns the count of all records that match the specified search criteria irrespective of their contents.

#### Sintaxe

DCOUNTA (Base de Datos; DatabaseField; campo de busca)

#### Exemplo

The example database table giving information about the guests invited to Joe’s birthday party (described above) should occupy cells A1:E10. The content of cells A12:E12 should be identical to the header labels for the database table in cells A1:E1. Make sure that cells A13:E13 are blank, except for cell D13 which should contain ">600" (this search criterion will match records in the database table that have a value greater than 600 in the Distance column).

Insert the formula =DCOUNTA(A1:E10;; A12:E13) into an empty cell elsewhere in the sheet to calculate how many of Joe’s party guests travel further than 600 meters to school. The value 5 is returned.

The same result is obtained if you use the formula =DCOUNTA(A1:E10; "Distance"; A12:E13) or the formula =DCOUNTA(A1:E10; "Name"; A12:E13). The latter case reflects that in contrast to DCOUNT, DCOUNTA counts both numeric and alphanumeric values in the column indicated by the DatabaseField argument.

## BDDESVEST

DSTDEV calculates the sample standard deviation based on the numeric values in the cells (fields) of the specified column, for all rows (database records) that match the specified search criteria. Non-numeric values are ignored.

Returns a #NUM! error if exactly one record matches the specified search criteria, or if there is only one numeric value in the cells of the specified column for the matching records.

Returns 0 if no matches are found, or if there are no numeric values in the cells of the specified column for the matching records.

#### Sintaxe

DSTDEV (Base de Datos; DatabaseField; campo de busca)

#### Exemplo

The example database table giving information about the guests invited to Joe’s birthday party (described above) should occupy cells A1:E10. The content of cells A12:E12 should be identical to the header labels for the database table in cells A1:E1. Make sure that cells A13:D13 are blank and that cell E13 contains ">0" (this search criterion is intended to match all records in the database table).

Insert the formula =DSTDEV(A1:E10; "Weight"; A12:E13) into an empty cell elsewhere in the sheet to calculate the sample standard deviation of the weights in kg of Joe’s party guests. The value 5.5 is returned.

## BDDESVESTP

DSTDEVP calculates the population standard deviation based on the numeric values in the cells (fields) of the specified column, for all rows (database records) that match the specified search criteria. Non-numeric values are ignored.

Returns a #NUM! error if no records match the specified search criteria, or if there are no numeric values in the cells of the specified column for the matching records.

#### Sintaxe

DSTDEVP (Base de Datos; DatabaseField; campo de busca)

#### Exemplo

The example database table giving information about the guests invited to Joe’s birthday party (described above) should occupy cells A1:E10. The content of cells A12:E12 should be identical to the header labels for the database table in cells A1:E1. Make sure that cells A13:D13 are blank and that cell E13 contains ">0" (this search criterion is intended to match all records in the database table).

Insert the formula =DSTDEVP(A1:E10; "Weight"; A12:E13) into an empty cell elsewhere in the sheet to calculate the population standard deviation of the weights in kg of Joe’s party guests. The value 5.18545 is returned.

## BDMEDIA

DAVERAGE calculates the average of the numeric values in the cells (fields) of the specified column, for all rows (database records) that match the specified search criteria. Non-numeric values in those cells are ignored.

Returns a #DIV/0! error if no records match the specified search criteria, or if there are no numeric values in the cells of the specified column for the matching records.

#### Sintaxe

DAVERAGE (Base de Datos; DatabaseField; campo de busca)

#### Exemplo

The example database table giving information about the guests invited to Joe’s birthday party (described above) should occupy cells A1:E10. The content of cells A12:E12 should be identical to the header labels for the database table in cells A1:E1. Make sure that cells A13:E13 are blank, except for cell D13 which should contain ">0" (this search criterion is intended to match all records in the database table).

Insert the formula =DAVERAGE(A1:E10; "Distance"; A12:E13) into an empty cell elsewhere in the sheet to calculate the average distance in meters travelled to school by Joe’s party guests. The value 666.67 is returned.

## BDMÁX

DMAX calculates the maximum value across the cells (fields) of the specified column that contain numeric values, for all rows (database records) that match the specified search criteria. Blank cells or cells containing non-numeric characters are not included.

Devolve 0 se non se atopa ningunha coincidencia ou de non existiren valores numéricos distintos de cero nas celas da columna especificada para os rexistros correspondentes.

#### Sintaxe

DMAX (Base de Datos; DatabaseField; campo de busca)

#### Exemplo

The example database table giving information about the guests invited to Joe’s birthday party (described above) should occupy cells A1:E10. The content of cells A12:E12 should be identical to the header labels for the database table in cells A1:E1. Make sure that cells A13:E13 are blank, except for cell D13 which should contain ">0" (this search criterion is intended to match all records in the database table).

Insert the formula =DMAX(A1:E10; "Distance"; A12:E13) into an empty cell elsewhere in the sheet to find the maximum distance in meters that any of Joe’s party guests travel to school. The value 1200 is returned.

## BDMÍN

DMIN calculates the minimum value across the cells (fields) of the specified column that contain numeric values, for all rows (database records) that match the specified search criteria. Blank cells or cells containing non-numeric characters are not included.

Returns 0 if no matches are found, or if there are no non-zero numeric values in the cells of the specified column for the matching records.

#### Sintaxe

DMIN (Base de Datos; DatabaseField; campo de busca)

#### Exemplo

The example database table giving information about the guests invited to Joe’s birthday party (described above) should occupy cells A1:E10. The content of cells A12:E12 should be identical to the header labels for the database table in cells A1:E1. Make sure that cells A13:E13 are blank, except for cell D13 which should contain ">0" (this search criterion is intended to match all records in the database table).

Insert the formula =DMIN(A1:E10; "Distance"; A12:E13) into an empty cell elsewhere in the sheet to find the minimum distance in meters that any of Joe’s party guests travel to school. The value 150 is returned.

## BDOBTER

DGET returns the contents of the cell (field) of the specified column, for the single row (database record) that matches the specified search criteria.

Calc reports Err:502 (invalid argument) if multiple matches are found, or a #VALUE! error (wrong data type) if no matches are found. A #VALUE! error is also reported if a single match is found but the relevant cell is empty.

#### Sintaxe

DGET (Base de Datos; DatabaseField; campo de busca)

#### Exemplo

The example database table giving information about the guests invited to Joe’s birthday party (described above) should occupy cells A1:E10. The content of cells A12:E12 should be identical to the header labels for the database table in cells A1:E1. Make sure that cells A13:E13 are blank, except for cell C13 which should contain "11" (this search criterion will match records in the database table that have a value of 11 in the Age column).

Insert the formula =DGET(A1:E10; "Name"; A12:E13) into an empty cell elsewhere in the sheet to find the name of Joe’s party guest who is age 11. The name Daniel is returned.

If you change the value in cell C13 to “10”, then the formula =DGET(A1:E10; "Name"; A12:E13) returns an invalid argument error (Err:502). The reflects that multiple records match the specified criterion (both Betty and Charles are age 10).

## BDPRODUTO

DPRODUCT calculates the product of all numeric values in the cells (fields) of the specified column, for all rows (database records) that match the specified search criteria. Blank cells or cells containing non-numeric characters are not included.

Returns 0 if no matches are found, or if there are no numeric values in the cells of the specified column for the matching records.

#### Sintaxe

DPRODUCT (Base de Datos; DatabaseField; campo de busca)

#### Exemplo

The example database table giving information about the guests invited to Joe’s birthday party (described above) should occupy cells A1:E10. The content of cells A12:E12 should be identical to the header labels for the database table in cells A1:E1. Make sure that cells A13:E13 are blank, except for cell C13 which should contain ">0" (this search criterion is intended to match all records in the database table).

Insert the formula =DPRODUCT(A1:E10; "Age"; A12:E13) into an empty cell elsewhere in the sheet to calculate the product of the ages in years of Joe’s party guests. The value 279417600 is returned.

## BDSUMA

DSUM calculates the sum of all numeric values in the cells (fields) of the specified column, for all rows (database records) that match the specified search criteria. Blank cells or cells containing non-numeric characters are not included.

Returns 0 if no matches are found, or if there are no numeric values in the cells of the specified column for the matching records.

#### Sintaxe

DSUM (Base de Datos; DatabaseField; campo de busca)

#### Exemplo

The example database table giving information about the guests invited to Joe’s birthday party (described above) should occupy cells A1:E10. The content of cells A12:E12 should be identical to the header labels for the database table in cells A1:E1. Make sure that cells A13:E13 are blank, except for cell D13 which should contain ">0" (this search criterion is intended to match all records in the database table).

Insert the formula =DSUM(A1:E10; "Distance"; A12:E13) into an empty cell elsewhere in the sheet to find the total distance in meters that all of Joe’s party guests travel to school. The value 6000 is returned.

## BDVAR

DVAR calculates the sample variance based on the numeric values in the cells (fields) of the specified column, for all rows (database records) that match the specified search criteria. Non-numeric values are ignored.

Returns a #NUM! error if exactly one record matches the specified search criteria, or if there is only one numeric value in the cells of the specified column for the matching records.

Returns 0 if no matches are found, or if there are no numeric values in the cells of the specified column for the matching records.

#### Sintaxe

DVAR (Base de Datos; DatabaseField; campo de busca)

#### Exemplo

The example database table giving information about the guests invited to Joe’s birthday party (described above) should occupy cells A1:E10. The content of cells A12:E12 should be identical to the header labels for the database table in cells A1:E1. Make sure that cells A13:E13 are blank, except for cell D13 which should contain ">0" (this search criterion is intended to match all records in the database table).

Insert the formula =DVAR(A1:E10; "Distance"; A12:E13) into an empty cell elsewhere in the sheet to find the sample variance of the distances in meters that Joe’s party guests travel to school. The value 193125 is returned.

## BDVARP

DVARP calculates the population variation based on the numeric values in the cells (fields) of the specified column, for all rows (database records) that match the specified search criteria. Non-numeric values are ignored.

Returns a #NUM! error if no records match the specified search criteria, or if there are no numeric values in the cells of the specified column for the matching records.

#### Sintaxe

DVARP (Base de Datos; DatabaseField; campo de busca)

#### Exemplo

The example database table giving information about the guests invited to Joe’s birthday party (described above) should occupy cells A1:E10. The content of cells A12:E12 should be identical to the header labels for the database table in cells A1:E1. Make sure that cells A13:E13 are blank, except for cell D13 which should contain ">0" (this search criterion is intended to match all records in the database table).

Insert the formula =DVARP(A1:E10; "Distance"; A12:E13) into an empty cell elsewhere in the sheet to find the population variance of the distances in meters that Joe’s party guests travel to school. The value 171666.67 is returned.

Temas relacionados

Funcións por categoría