如何过滤条件为 SQL 的行?

How to filter rows with condition in SQL?

我正在尝试使用以下查询从 Athena 检索数据:

SELECT DISTINCT cop.shop_id,
         cop.product_id,
         avg(cop.position) AS avg_position,
         cp.kes
FROM data_1 AS cop
JOIN data_2 AS cp
    ON cop.product_id = cp.product_id
WHERE cop.site_id = 1
        AND cop.product_id IS NOT NULL
GROUP BY  cop.shop_id, cop.product_id, cp.kes 

然而,数据中有四列:product_id、shop_id、avg_position、kes。

某些行在 kes 列中同时带有 NA 和非 NA。我只想在以下条件下操作数据:

我该怎么做?

我认为您希望在 kes:

上进行聚合
SELECT 
    cop.shop_id,
    cop.product_id,
    AVG(cop.position) AS avg_position,
    MAX(cp.kes) kes
FROM data_1 AS cop
JOIN data_2 AS cp
    ON cop.product_id = cp.product_id
WHERE cop.site_id = 1 AND cop.product_id IS NOT NULL
GROUP BY cop.shop_id, cop.product_id 

聚合函数忽略 null 个值;所以 MAX(cp.kes) 为您提供 cp.kes 的最高非 null 值。另一方面,如果 cp.kes 的所有值都在组内 null,则 max() 给出 null.

旁注:DISTINCTGROUP BY 放在一起没有意义(尽管 SQL 仍然有效); GROUP BY 保证 SELECT 列表中没有重复值。