如何将单行中的字段添加到行聚合 sql

How to add field from a single row to aggregate of rows presto sql

我想快速查询 return 某个人吃掉的水果总数。我还要加上最近一次吃水果的时间。

这是我的查询:

SELECT 
  id,
  fruittype,
  count(*) as fruitconsumptioncount
FROM
  (VALUES
    ( 'John', 'apple', '2017-10-15 16:35:27.000'),
    ( 'John', 'apple', '2017-10-16 16:35:27.000'),
    ( 'John', 'apple', '2017-10-17 16:35:27.000'),
    ( 'John', 'orange', '2017-10-14 16:35:27.000'),
    ( 'John', 'orange', '2017-10-15 16:35:27.000'),
    ( 'John', 'orange', '2017-10-20 16:35:27.000'),
    ( 'John', 'banana', '2017-10-18 16:35:27.000'),
    ( 'Bob', 'kiwi', '2017-10-15 16:35:27.000')
  ) as dimensions (id, fruittype, consumptiontime) 
GROUP BY
  id,
  fruittype
ORDER BY
  id,
  fruitconsumptioncount DESC`

这个returns:

id     fruittype    fruitconsumptioncount
Bob     kiwi         1
John    apple        3
John    orange       3
John    banana       1

我需要它 return:

id     fruittype    fruitconsumptioncount mostrecentconsumption
Bob     kiwi         1                     2017-10-15 16:35:27.000
John    apple        3                     2017-10-17 16:35:27.000
John    orange       3                     2017-10-20 16:35:27.000
John    banana       1                     2017-10-18 16:35:27.000

这是因为我想最终对每个人的顶级水果类型进行排序,但在并列的情况下,我想return最近吃过的并列水果。

假设你的Table是A:

A:
        id    fruittype   consumptiontime
    ----------------------------------------------- 
    ( 'John', 'apple', '2017-10-15 16:35:27.000'),
    ( 'John', 'apple', '2017-10-16 16:35:27.000'),
    ( 'John', 'apple', '2017-10-17 16:35:27.000'),
    ( 'John', 'orange', '2017-10-14 16:35:27.000'),
    ( 'John', 'orange', '2017-10-15 16:35:27.000'),
    ( 'John', 'orange', '2017-10-20 16:35:27.000'),
    ( 'John', 'banana', '2017-10-18 16:35:27.000'),
    ( 'Bob', 'kiwi', '2017-10-15 16:35:27.000')

所以,如果 consumptiontimeDateTime 数据类型或类似的东西,试试这个:

SELECT id, fruittype, count(*) as fruitconsumptioncount, max(consumptiontime)
FROM A  
GROUP BY id, fruittype 
ORDER BY id, fruitconsumptioncount DESC

如果是字符串,就转换成日期。
参见:Presto SQL - Converting a date string to date format