Athena SQL 在一列上不同但返回几列?

sha*_*313 3 sql distinct amazon-athena

我似乎无法找到一个简单的答案,而且我是 SQL 初学者,我正在 Amazon Athena 中执行此操作。我想在一列上有一个不同的结果,但返回几个没有不同的结果。这是我的代码:

SELECT DISTINCT line_item_resource_id
FROM table
WHERE product_servicename = 'Amazon Elastic Compute Cloud'
AND line_item_usage_account_id = '544934960'
AND line_item_usage_type LIKE '%BoxUsage%'
AND identity_time_interval = '2020-06-29T00:00:00Z/2020-06-30T00:00:00Z';
Run Code Online (Sandbox Code Playgroud)

我希望 unique 只出现在 line_item_resource_id 上,但返回所有这些:

line_item_resource_id, line_item_usage_start_date, 
line_item_usage_end_date, line_item_usage_account_id, 
line_item_availability_zone, line_item_product_code, product_instance_type, 
pricing_term, product_operating_system, product_servicename, 
line_item_line_item_type, line_item_usage_type, line_item_operation, 
line_item_usage_amount
Run Code Online (Sandbox Code Playgroud)

此代码仅产生 line_item_resource_id 。如何仅获得该列上的不同值但返回其余部分?

Cha*_*l P 5

我想在这里建议另一个解决方案,使用ROW_NUMBER()

我将在这里展示基本的解决方案,当然 ROW_NUMBER() 有更多的可能性(比如在分区中执行 order by 等等..

在此解决方案中,您不需要在每一列之前编写聚合函数,您只需使用*. 这使得查询变得更短、更清晰。

所以你可以这样做:

WITH tmp_table AS (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY line_item_resource_id) rn
  FROM table
  WHERE product_servicename = 'Amazon Elastic Compute Cloud'
    AND line_item_usage_account_id = '544934960'
    AND line_item_usage_type LIKE '%BoxUsage%'
    AND identity_time_interval = '2020-06-29T00:00:00Z/2020-06-30T00:00:00Z'
)    
SELECT *
FROM tmp_table
WHERE rn = 1
Run Code Online (Sandbox Code Playgroud)