【问题标题】:How can I count a subquery with group by如何使用 group by 计算子查询
【发布时间】:2020-07-21 10:02:26
【问题描述】:

我是新来的,我是法国人,请原谅我的英语。

我有一个带有 HQL 源的网格。 第一个 HQL 的查询发送记录数,第二个查询数据。 但是第一次查询的结果不等于第二次查询的记录数。

第一次查询(返回26条记录):

SELECT 
    resou.res_book.res_book_id as record,
    strset.str_set_cd as room, 
    concat(coalesce(person.firstname, ' '), ' ', coalesce(person.lastname, ' ')) as name, 
    prod_h.d_from_d as start_date,
    prod_h.d_to_d as end_date,
    (SUM(prod_h.amt_total_ivat) - SUM(pay_l.amt_paymt)) as total
FROM Com_site as site
inner join site.com_bu as bu
inner join bu.com_activ as activ
inner join activ.inv_head as head
inner join head.inv_person as person
inner join person.res_rooming as rooming
inner join rooming.res_resou as resou
inner join resou.str_set as strset
inner join person.inv_prod_h as prod_h
inner join head.inv_pay_l as pay_l
inner join prod_h.pdt_prod as prod
WHERE
    head.tp_folio_tp = 0 and
    prod_h.d_to_d <= '2020-07-01' and
    site.com_site_id = 1 and
    prod_h.inv_accou_itm.inv_accou_itm_id is null and
    prod.b_rent_bl = false and
    '2020-07-01' between resou.d_from_d and resou.d_to_d
GROUP BY 
    head.inv_head_id
    , person.firstname
    , person.lastname
    , strset.str_set_cd
    , resou.res_book.res_book_id
    , prod_h.d_from_d
    , prod_h.d_to_d
    , head.tp_folio_tp
    , prod.pdt_prod_id

第二个查询(返回1条记录但值为316(不是26)):

select 
(
    SELECT 
        COUNT(head.inv_head_id) as counted
    from site.com_bu as bu
    inner join bu.com_activ as activ
    inner join activ.inv_head as head
    inner join head.inv_person as person
    inner join person.res_rooming as rooming
    inner join rooming.res_resou as resou
    inner join resou.str_set as strset
    inner join person.inv_prod_h as prod_h
    inner join head.inv_pay_l as pay_l
    inner join prod_h.pdt_prod as prod
    WHERE
        head.tp_folio_tp = 0 and
        prod_h.d_to_d <= '2020-07-01' and
        site.com_site_id = 1 and
        prod_h.inv_accou_itm.inv_accou_itm_id is null and
        prod.b_rent_bl = false and
        '2020-07-01' between resou.d_from_d and resou.d_to_d
) as counted
from Com_site as site

我试过了:
COUNT(COUNT(head.inv_head_id)), COUNT(*the subquery here*)

但没有任何效果...

谁能帮帮我?

先谢谢你了。

【问题讨论】:

  • 您是否尝试在第二个查询中添加GROUP BY?它可能会过滤掉来自1:N 关系的一些重复记录。
  • 您对第二个查询有何期望?你说它应该返回数据但是有一个计数

标签: java hibernate hql


【解决方案1】:

我不太明白你为什么要先确定计数,然后查询所有数据,你可以通过计算获取的实体数量来确定计数,所以不需要第二次查询。

如果你想实现分页,我建议你看看Blaze-Persistence,它对creating efficient count queries from a base querybounded counting有很好的支持,而且还支持各种分页技术:https://persistence.blazebit.com/documentation/core/manual/en_US/index.html#pagination

【讨论】:

    【解决方案2】:

    谢谢你帮助我!我发现我的查询完全错误,所以我重写了没有 group by 的查询,它的工作原理!第一个查询发送第二个查询的正确记录计数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多