Couchbase N1QL子选择与GROUP BY结合使用

时间:2017-03-31 14:44:34

标签: subquery grouping couchbase n1ql

我有以下航班报价数据结构:

IXpsOMObjectFactory* fXpsFactory;

HRESULT hr = CoCreateInstance(
    CLSID_XpsOMObjectFactory,
    nullptr,
    CLSCTX_INPROC_SERVER,
    IID_PPV_ARGS(&fXpsFactory));

{ "offerIdentifier": "123", "flyFrom": "HAM", "flyTo": "LGW", "provider": "LH", "price": 207, "bookingUrl": "https://example.com/", "flightCombinationIdentifier": "HAM-LGW-201791570-20179171835" } 属性的值可以显示在多个商品上。

现在我想按flightCombinationIdentifier进行分组,找到这个组合的最低价格,理想情况下应该会产生这样的结构:

flightCombinationIdentifier

所以我提出了以下N1QL查询:

{
  "offerIdentifier": "456",
  "flightCombinationIdentifier": "HAM-LGW-201791570-20179171835",
  "offer": [
    {
      "bookingUrl": "http://example.com/",
      "price": 97,
      "provider": "LH"
    }
  ]
}

不幸的是,它因以下错误而死亡:

select b.flightCombinationIdentifier,
    (
        select b1.price, b1.provider, b1.bookingUrl from bucket b1
        use keys b.offerIdentifier
        where b1.flightCombinationIdentifier = b.flightCombinationIdentifier
        order by b1.price asc
        limit 1
    ) as offer

from bucket b
where b.flyFrom = 'HAM' and b.flyTo = 'LGW'
group by b.flightCombinationIdentifier

将子查询的结果输入结果对象的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

SELECT flightCombinationIdentifier, MIN([price, {bookingUrl,price,provider}])[1] AS offer
FROM bucket WHERE flyFrom = 'HAM' AND flyTo = 'LGW'
GROUP BY flightCombinationIdentifier;