如何获得最大价值的行?

时间:2019-12-02 06:45:35

标签: google-cloud-spanner

我认为可行的是:

SELECT *
FROM customer_sale
WHERE sale_date < '2019-02-01'
GROUP BY customer_id
HAVING sale_date = MAX(sale_date)

但是运行此命令会导致错误

  

HAVING子句表达式引用列sale_date,该列为   既不是分组也不是聚集

在Spanner中还有另一种方法可以实现这一目标吗?更普遍地说,为什么不允许上述内容?

修改

customer_sale表中的数据示例:

customer_id         sale_date
-------------------------------
    1                  Jan 15
    1                  Jan 30
    1                  Feb 2
    1                  Feb 4
    2                  Jan 15
    2                  Feb 2

预期结果:

customer_id         sale_date
-------------------------------
    1                  Jan 30
    2                  Jan 15

2 个答案:

答案 0 :(得分:1)

  

SQL中的HAVING子句指定应使用SQL SELECT语句   仅返回合计值满足指定条件的行。   它被添加到SQL语言中,因为WHERE关键字不能   与aggregate functions

一起使用

这是我正在使用的测试表:

index, customer_id, sale_date 

1   1   2017-08-25T07:00:00Z 

2   1   2017-08-26T07:00:00Z 

3   1   2017-08-27T07:00:00Z 

4   1   2017-08-28T07:00:00Z 

5   2   2017-08-29T07:00:00Z 

6   2   2017-08-30T07:00:00Z

使用此查询:

 Select customer_id, max(sale_date) as max_date
 from my_test_table
 group by customer_id;

我得到以下结果:

 customer_id    max_date

 1              2017-08-28T07:00:00Z

 2              2017-08-30T07:00:00Z

还包括where语句:

 Select customer_id, max(sale_date) as max_date
 from my_test
 where sale_date < '2017-08-28'
 group by customer_id;

答案 1 :(得分:0)

我遇到了同样的问题,这样我就能解决。如果您的桌子很大,则可能需要一些时间。

基本上,将普通表与具有最大值记录的表连接即可解决此问题。

select c.* from 
(select * from customer_sale WHERE sale_date < '2019-02-01') c
inner join 
(SELECT customer_id, max(sale_date) as max_sale_date FROM customer_sale WHERE 
sale_date < '2019-02-01' group by customer_id) max_c
on c.customer_id = max_c.customer_id and c.sale_date = max_c.sale_date