我有下表:
portal=# \d+ accounts_version
Table "public.accounts_version"
Column | Type | Modifiers | Storage | Stats target | Description
--------------------------+-----------------------------+-----------+----------+--------------+-------------
id | integer | not null | plain | |
status | account_status | | plain | |
adwords_id | character varying(20) | | extended | |
nickname | character varying(48) | | extended | |
account_budget | double precision | | plain | |
remaining_account_budget | double precision | | plain | |
daily_budget | double precision | | plain | |
currency | character varying(12) | | extended | |
exchange_rate | double precision | | plain | |
login | character varying(48) | | extended | |
password | character varying(48) | | extended | |
billing | character varying(48) | | extended | |
auto_tag_on | boolean | | plain | |
mcc_id | integer | | plain | |
vps_id | integer | | plain | |
client_id | integer | | plain | |
transaction_id | bigint | not null | plain | |
end_transaction_id | bigint | | plain | |
operation_type | smallint | not null | plain | |
country | character varying(24) | | extended | |
external_comment | text | | extended | |
internal_comment | text | | extended | |
batch | character varying(48) | | extended | |
updated_at | timestamp without time zone | | plain | |
Indexes:
"accounts_version_pkey" PRIMARY KEY, btree (id, transaction_id)
"ix_accounts_version_end_transaction_id" btree (end_transaction_id)
"ix_accounts_version_operation_type" btree (operation_type)
"ix_accounts_version_transaction_id" btree (transaction_id)
我正在尝试查询每个adwords_id的最新条目。
所以我开始写这样的SQL查询:
SELECT * FROM accounts_version GROUP BY adwords_id;
我收到以下错误:
ERROR: column "accounts_version.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT * FROM accounts_version
^
我正在运行postgres 9.5。知道是什么导致了这个吗?
答案 0 :(得分:0)
PostgreSQL GROUP BY将列组表达式作为输入,当列为text类型且未在聚合函数中使用时会引发错误请参阅SELECT - GROUP BY- Transact-SQL
答案 1 :(得分:0)
GROUP BY
不是正确的方法。你想要的是DISTINCT ON
。要获取每个updated_at
的最新adwords_id
行,请尝试以下操作:
SELECT DISTINCT ON (adwords_id) *
FROM accounts_version
ORDER BY updated_at DESCENDING;