0

我有看起来像这样的数据集:

|---------------------|------------------|------------------|
|          ID         |        Date      |       Cost       |
|---------------------|------------------|------------------|
|          1          |       9/15/20    |       $500       |
|---------------------|------------------|------------------|
|          1          |       9/30/20    |       $600       |
|---------------------|------------------|------------------|
|          1          |       10/2/20    |       $400       |
|---------------------|------------------|------------------|
|          2          |       10/10/20   |       $1,000     |
|---------------------|------------------|------------------|
|          3          |       9/29/20    |       $600       |
|---------------------|------------------|------------------|
|          3          |       10/5/20    |       $400       |
|---------------------|------------------|------------------|
|          3          |       10/6/20    |       $800       |
|---------------------|------------------|------------------|
|          3          |       10/10/20   |       $200       |
|---------------------|------------------|------------------|

在 Looker 中使用 SQL Runner,我只想为每个 ID 保留每个月可用的最新日期的行。所以我的示例表最终应该是这样的:

|---------------------|------------------|------------------|
|          ID         |        Date      |       Cost       |
|---------------------|------------------|------------------|
|          1          |       9/30/20    |       $600       |
|---------------------|------------------|------------------|
|          1          |       10/2/20    |       $400       |
|---------------------|------------------|------------------|
|          2          |       10/10/20   |       $1,000     |
|---------------------|------------------|------------------|
|          3          |       9/29/20    |       $600       |
|---------------------|------------------|------------------|
|          3          |       10/10/20   |       $200       |
|---------------------|------------------|------------------|
4

2 回答 2

0

You can use row_number() if your DBMS supports it

select id, date, cost from
(
  select id, date, cost,
         row_number() over(partition by id order by date desc) as rn
from tablename
)A where rn<=2
于 2020-10-12T16:11:51.163 回答
0

以下应该在几乎任何数据库上运行:

select id, month(date), max(date) as latest_date_in_month
from <TABLE>
group by id, month(date)
order by id, month(date)
于 2020-12-02T12:04:54.483 回答