带有标记值的 GROUP BY

GROUP BY with flagged value

下面的查询是 return 标记为 Y if c.LAST_UPDATED_TIMESTAMP < MAX(t.LATEST_ACTION_TIMESTAMP)

SELECT
'Y' as CAN_UPDATE, t.LATEST_ACTION_TIMESTAMP
FROM CUSTOMERS c
LEFT JOIN TRANSACTIONS t ah on (c.customer_id = t.customer_id)
WHERE
t.status_active_flag = 'Y' and  c.customer_ID ='CUST_019'
GROUP BY t.LATEST_ACTION_TIMESTAMP
HAVING c.LAST_UPDATED_TIMESTAMP < MAX(t.LATEST_ACTION_TIMESTAMP);

ORA-00979 不是遇到 GROUP BY 表达式,理解 SELECT 中的所有列都需要包含在 GROUP BY 子句中。在这种情况下如何处理标记值 'Y'?

第 c.LAST_UPDATED_TIMESTAMP 列也需要按部分添加到组中

GROUP BY t.LATEST_ACTION_TIMESTAMP, c.LAST_UPDATED_TIMESTAMP

这里有一个 dbfiddle 和一个愚蠢的例子

HAVING 子句将有效地将 LEFT JOIN 更改为 INNER JOIN 并且您可以,因为您正在获取要分组的列的最大值并在该列上聚合是无关紧要的,因为每个组只有一个奇异值,然后将 HAVING 比较移动到没有聚合的连接的 ON 子句:

SELECT 'Y' as CAN_UPDATE,
       t.LATEST_ACTION_TIMESTAMP
FROM   CUSTOMERS c
       INNER JOIN TRANSACTIONS t
       ON (   c.customer_id = t.customer_id
          AND c.LAST_UPDATED_TIMESTAMP < t.LATEST_ACTION_TIMESTAMP
          )
WHERE  t.status_active_flag = 'Y'
AND    c.customer_id ='CUST_019'
GROUP BY t.LATEST_ACTION_TIMESTAMP;

您也可以使用 DISTINCT(或 UNIQUE)子句代替 GROUP BY 子句。