postgresql SQL中的最大多列数

xam8gpfp  于 2023-06-29  发布在  PostgreSQL
关注(0)|答案(1)|浏览(166)

我从一个旧的堆栈帖子中找到了这个很好的解决方案:https://stackoverflow.com/a/6871572/194653
但由于某种原因,它对我不起作用,这是我需要执行以获取最大值的查询:

Select a.id as id, first_name as name, surname, h.maiden_name, c.salutation, c.gender, coalesce (d.marital_status,’Z’) as marital_status, coalesce (g.occupation, ‘0047’) as occupation, coalesce (f.kind_of_work, '9') as kind_of_work,‘’ as change_type
(SELECT Max (date_last_mod)
FROM (VALUES (a.date_last_mod), (c.date_last_mod),(d.date_last_mod),
(f.date_last_mod), (g.date_last_mod), (h.date_last_mod)) AS value (date_last_mod)) as date_last_mod

from people.al_names_spk a

inner join people.al_salutation_spk c
on a.id = c.id
left join people.al_marital_status_spk d
on a.id = d.id
left join people.al_kind_of_work_spk f
on a.id = f.id
inner join people.al_occupation_spk g
on a.id = a.id
left join people.al_maiden_name_spk h
a.id = h.id
LEFT SEMI JOIN people_st.stg_person_hist_spk b ON (a.id = b.id AND b.data_date_part = '2023-06-01’)

我也尝试了其他可能的解决方案来选择最大值,但它不起作用:

(SELECT MAX(date_last_mod) FROM (
    SELECT a.date_last_mod
    UNION ALL
    SELECT c.date_last_mod
    UNION ALL
    SELECT d.date_last_mod
    UNION ALL
    SELECT f.date_last_mod
    UNION ALL
    SELECT g.date_last_mod
    UNION ALL
    SELECT h.date_last_mod ) AS value(date_last_mod)) AS date_last_mod

我做错什么了吗?每次我执行这个,我有一个语法错误消息。我不得不说,我正在顺化执行这一点。

**UPDATE:**错误信息:

AnalysisException: Syntax error in line 37:undefined: (SELECT Max(date_last_mod) ^ Encountered: SELECT Expected: ALL, CASE, CAST, DEFAULT, DISTINCT, EXISTS, FALSE, IF, INTERVAL, LEFT, NOT, NULL, REPLACE, RIGHT, TRUNCATE, TRUE, IDENTIFIER CAUSED BY: Exception: Syntax error

感谢阅读。

x33g5p2x

x33g5p2x1#

可以使用GREATEST来获取同一行中多列的最大值。
然后,您可以使用MAX将每行的最大值(由GREATEST计算)聚合为所需行的总MAX

SELECT MAX(GREATEST(a.date_last_mod, b.date_last_mod, c.date_last_mod))
FROM table_a a
    LEFT JOIN table_b b ON a.id=b.id
    LEFT JOIN table_c b ON a.id=c.id

根据您编写整体查询的方式,您也可以反过来执行:计算每个MAXGREATEST
(In在某些情况下,我怀疑它可能会执行得更好,因为如果这些列被单独索引,那么MAX per column first可能能够使用基于索引的优化。也就是说,这取决于你的指数。)

相关问题