【问题标题】:Recreating an SQL query in JavaScript ES6在 JavaScript ES6 中重新创建 SQL 查询
【发布时间】:2021-05-11 21:52:31
【问题描述】:

我正在尝试在 JavaScript 中重建一个大型 SQL 管道,以便它可以作为无服务器 CRON 作业运行,而无需启动新数据库。在我处理它的过程中,我的数据看起来像这样:

const orders = [
    { email: 'test@test.com', orders: '11111111', daydate: 2017-07-29, revenue: 59.99 },
    { email: 'test1@test1.com', orders: '22222222', daydate: 2015-07-29, revenue: 52.99 },
...
]

下一个 SQL 查询在这里:

SELECT
    DISTINCT(email),
    EXTRACT(month from min(daydate)) as month_acquired,
    EXTRACT(year from min(daydate)) as year_acquired
FROM orders
GROUP BY email

我想知道在 JavaScript 中重建此查询的最佳方法是什么?

我开始尝试使用以下语句获取不同的电子邮件:

const distinctEmails = orders.filter((elem, index) => orders.findIndex(obj => obj.email === elem.email) === index)

但是这个调用耗时很长(我的数据集很大),只满足SQL查询的第一个操作。

我应该怎么做?

编辑:我希望(SQL -> JS)的输出如下:

[
  {email: 'test@test.com', month_acquired: 07, year_acquired: 2017},
  {email: 'test1@test1.com', month_acquired: 07, year_acquired: 2015}
]

【问题讨论】:

  • 你能展示一下数据的结果应该是什么样子吗?
  • new Map(items.sort((a,b) => b.daydate - a.daydate).map(v => [v.email, v.daydate])) 可以做除了EXTRACT 之外的所有事情。假设 daydateDate 对象或时间戳。

标签: javascript sql node.js ecmascript-6


【解决方案1】:

这最终对我有用:

  const res = o.reduce((r, o) => {
    const key = o.email
    const monthAcquired = parseInt(o.daydate.split('-')[1])
    const yearAcquired = parseInt(o.daydate.split('-')[0])
    if (!r[key]) {
      r[key] = { email: o.email, month_acquired: monthAcquired, year_acquired: yearAcquired }
    } else {
      if (r[key].year_acquired > yearAcquired) {
        r[key].year_acquired = yearAcquired
        r[key].month_acquired = monthAcquired
      } else {
        if (r[key].year_acquired === yearAcquired && r[key].month_acquired > monthAcquired) {
          r[key].year_acquired = yearAcquired
          r[key].month_acquired = monthAcquired
        }
      }
    }
    return r
  }, {})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 2011-10-22
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    相关资源
    最近更新 更多