You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PostgreSQL的CTE或子查询中引用DISTINCT后的列名?

Fixing the "column does not exist" Error with DISTINCT in PostgreSQL

The issue here is how you’re using DISTINCT. When you write DISTINCT(col1, col2), PostgreSQL interprets this as creating a single composite row column (containing both col1 and col2 values) rather than selecting distinct pairs of the two separate columns. That’s why you can’t reference col1 or col2 directly later—those columns don’t exist in your CTE/subquery; instead, there’s one column with a row type.

Here’s how to fix it:

Corrected CTE Approach

Remove the parentheses around col1 and col2 to get distinct pairs as separate columns:

WITH cte AS (
  SELECT DISTINCT col1, col2
  FROM table1
  WHERE col1 IS NOT NULL AND col2 IS NOT NULL
)
SELECT json_build_object('col1', cte.col1, 'col2', cte.col2) FROM cte;

Corrected Subquery Approach

Same fix applies here—use DISTINCT with the columns listed separately:

SELECT json_build_object('col1', col1, 'col2', col2)
FROM (
  SELECT DISTINCT col1, col2
  FROM table1
  WHERE col1 IS NOT NULL AND col2 IS NOT NULL
) AS temp;

Alternative: Using DISTINCT ON (If You Need Specific Rows)

If you ever need to pick a specific row for each unique (col1, col2) pair (e.g., the latest row), you can use PostgreSQL’s DISTINCT ON feature:

SELECT json_build_object('col1', col1, 'col2', col2)
FROM (
  SELECT DISTINCT ON (col1, col2) col1, col2
  FROM table1
  WHERE col1 IS NOT NULL AND col2 IS NOT NULL
  ORDER BY col1, col2 -- Add additional columns here to prioritize which row to keep
) AS temp;

This returns the first row for each unique combination of col1 and col2, ordered by the clauses you specify.

内容的提问来源于stack exchange,提问作者Abe Voelker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 13:24:06