Firebird group by,count和extract赋予表达式无效

时间:2017-07-20 16:10:23

标签: sql firebird

有人可以帮助我的sql吗? 我想计算我在表HISTORICO_ACESSO中有多少个同名的注册表。

我现在的sql是:

select
    (EXTRACT(DAY FROM ha.entrada)||'.'||EXTRACT(month FROM ha.entrada)||'.'||extract(YEAR FROM ha.entrada)) as DATA,
    coalesce(hae.os_exame, '-') as EXAME,
    coalesce((select nome from usuario u where ha.login = u.usuario), ha.login) as USUARIO,
    coalesce(hae.pagina, 'Visualização Listagem') as TIPO,
    COUNT(*) as QTDE

from
    historico_acesso ha
    left join historico_acesso_exame hae
    on ha.codigo = hae.cod_historico

group by
    DATA, EXAME,  USUARIO, TIPO

我有错误:

动态SQL错误。 SQL错误代码= -104。 选择列表中的表达式无效(不包含在聚合函数或GROUP BY子句中)。

我的DDL是:

CREATE TABLE HISTORICO_ACESSO (
    CODIGO        INTEGER NOT NULL,
    COD_REGISTRO  VARCHAR(200),
    USER_AGENT    VARCHAR(500),
    LOGIN         VARCHAR(100),
    NIVEL         VARCHAR(10),
    ENTRADA       TIMESTAMP NOT NULL,
    SAIDA         TIMESTAMP,
    IDIOMA        VARCHAR(10),
    INFO_EXTRAS   BLOB SUB_TYPE 0 SEGMENT SIZE 80
);

ALTER TABLE HISTORICO_ACESSO ADD PRIMARY KEY (CODIGO);

2 个答案:

答案 0 :(得分:2)

对于此查询,您需要使用派生表在对它们进行分组之前创建这些别名,或者您需要按列索引进行分组,因此要么使用:

select DATA, EXAME, USUARIO, TIPO, COUNT(*) as QTDE
from (
    select
        (EXTRACT(DAY FROM ha.entrada)||'.'||EXTRACT(month FROM ha.entrada)||'.'||extract(YEAR FROM ha.entrada)) as DATA,
        coalesce(hae.os_exame, '-') as EXAME,
        coalesce(u.nome, ha.login) as USUARIO,
        coalesce(hae.pagina, 'Visualização Listagem') as TIPO
    from historico_acesso ha
    left join historico_acesso_exame hae
        on ha.codigo = hae.cod_historico
    left join usuario u
        on ha.login = u.usario
) a
group by DATA, EXAME, USUARIO, TIPO

请注意,我还将usuario上的子选项更改为left join(不是非常必要,只是我的偏好)。使用派生表需要Firebird 2.0或更高版本。

或者,按列名称将组替换为按列索引分组:

group by 1, 2, 3, 4

答案 1 :(得分:0)

我认为Firebird不支持group by中的别名。试试这个:

select (EXTRACT(DAY FROM ha.entrada)||'.'||EXTRACT(month FROM ha.entrada)||'.'||extract(YEAR FROM ha.entrada)) as DATA,
       coalesce(hae.os_exame, '-') as EXAME,
       coalesce((select nome from usuario u where ha.login = u.usuario), ha.login) as USUARIO,
       coalesce(hae.pagina, 'Visualização Listagem') as TIPO,
       COUNT(*) as QTDE
from historico_acesso ha left join
     historico_acesso_exame hae
     on ha.codigo = hae.cod_historico
group by (EXTRACT(DAY FROM ha.entrada)||'.'||EXTRACT(month FROM ha.entrada)||'.'||extract(YEAR FROM ha.entrada)),
         coalesce(hae.os_exame, '-'),
         coalesce((select nome from usuario u where ha.login = u.usuario), ha.login),
         coalesce(hae.pagina, 'Visualização Listagem');