【问题标题】:Execute postgresql query for multiple input dates对多个输入日期执行 postgresql 查询
【发布时间】:2019-11-27 13:02:37
【问题描述】:

我有这个 postgres 查询:

select to_date('10.11.19','dd.mm.yy') as date,"licenseId",count("licenseId") as lizenseCount,round(sum("yearlyCostEurCents")::numeric/1200,2) as mrr
from "Subscription"
where "versionOf" < to_date('10.11.19','dd.mm.yy')
and not ( "cancelledAt" < to_date('10.11.19','dd.mm.yy') and  "isArchived")
group by "licenseId";

我想为日期数组执行它(['10.11.19','11.11.19',...]). 有没有办法在 postgresql 中做到这一点?

编辑:显然我不擅长提问...

我的意思是我有一个日期数组(类似于 (([date_1,date_2,...,date_n])),现在我想执行这个查询:对于数组中的每个日期。

select to_date(date_*,'dd.mm.yy') as date,"licenseId",count("licenseId") as lizenseCount,round(sum("yearlyCostEurCents")::numeric/1200,2) as mrr
from "Subscription"
where "versionOf" < to_date(date_*,'dd.mm.yy')
and not ( "cancelledAt" < to_date(date_*,'dd.mm.yy') and  "isArchived")
group by "licenseId";

有没有办法在 postgresql 中做到这一点?因为目前我的代码中有一个 for 循环可以执行此操作,但这当然非常慢。

【问题讨论】:

  • 您可以将数组转换为表格检查unnest函数。那么你可以在那个桌子上join / cross apply
  • 与您的问题无关,但是:您应该真正避免使用那些可怕的带引号的标识符。他们的麻烦比他们值得的要多得多。 wiki.postgresql.org/wiki/…
  • @ArjunVachhani:Postgres 或标准 SQL 中没有 cross apply。它在那里被称为横向连接,例如cross join lateral
  • @bear14:我不确定如何使用多个日期。如果"versionOf" &lt; '2019-11-10' 为真,那么显然versionof &lt; '2019-11-11 也为真,那么您究竟想如何比较数组元素呢?所以在数组中传递2019-11-10 2019-11-11 似乎没有多大意义

标签: sql arrays postgresql date


【解决方案1】:

如果你想要一个范围,你可以使用 where 子句:

  select to_date('10.11.19','dd.mm.yy') as date,
         "licenseId",count("licenseId") as lizenseCount,
         round(sum("yearlyCostEurCents")::numeric/1200,2) as mrr
    from "Subscription"
   where "versionOf" < to_date('10.12.19','dd.mm.yy') -- > 10.12.19
     and "versionOf" > to_date('10.11.19','dd.mm.yy') -- AND < 10.11.19
     and not ( "cancelledAt" > to_date('10.11.19','dd.mm.yy') and "cancelledAt < to_date('10.12.19', 'dd.mm.yy') and  "isArchived")
group by "licenseId";

如果您有一组特定的日期,您可以使用IN 子句获取一组元素以与列值进行比较。

  select to_date('10.11.19','dd.mm.yy') as date,
         "licenseId",count("licenseId") as lizenseCount,
         round(sum("yearlyCostEurCents")::numeric/1200,2) as mrr
    from "Subscription"
   where "versionOf" IN (to_date('10.11.19','dd.mm.yy'), to_date('11.11.19','dd.mm.yy'), to_date('12.11.19','dd.mm.yy'))
     and not ( "cancelledAt" IN (to_date('10.11.19','dd.mm.yy'), to_date('11.11.19','dd.mm.yy'), to_date('12.11.19','dd.mm.yy')) and  "isArchived")
group by "licenseId";

第一次选择,在时间复杂度上比第二次选择效率更高。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    • 1970-01-01
    相关资源
    最近更新 更多