1

我一直在为其他 StackOverflow 响应而苦苦挣扎。我想将查询的输出保存到本地文本文件 - 只要文本文件在我的本地机器上,它的位置并不重要。

我正在使用的代码:

\COPY (
select month,count(*) as distinct_Count_month 
from
(
select UNIQUE_MEM_ID,to_char(transaction_date, 'YYYY-MM') as month
FROM yi_fourmpanel.card_panel WHERE COBRAND_ID = '10006164'
group by UNIQUE_MEM_ID,to_char(transaction_date, 'YYYY-MM')
) a
group by month) TO 'mycsv.csv' WITH CSV HEADER;

此代码的错误是:

<!-- language: none -->

An error occurred when executing the SQL command:
\COPY (

ERROR: syntax error at or near "\"
  Position: 1

\COPY (
^

Execution time: 0.08s
(Statement 1 of 2 finished)

An error occurred when executing the SQL command:
select month,count(*) as distinct_Count_month 
from
(
select UNIQUE_MEM_ID,to_char(transaction_date, 'YYYY-MM') as month
FROM yi_fourmpanel.card_panel...

ERROR: syntax error at or near ")"
  Position: 260

group by month) TO 'mycsv.csv' WITH CSV HEADER
              ^

Execution time: 0.08s
(Statement 2 of 2 finished)

2 statements failed.
Script execution finished
Total script execution time: 0.16s
4

1 回答 1

0

1.对于服务器 COPY删除\并运行psql如下:

COPY (
WITH data(val1, val2) AS ( VALUES
  ('v1', 'v2')
)
SELECT *
FROM data
) TO 'yourServerPath/output.csv' CSV HEADER;

cat yourServerPath/output.csv

val1,val2
v1,v2

2.对于客户副本

psql -h host -U user -d database -c "\copy \
( \
  WITH data(val1, val2) AS ( VALUES \
    (1, 2) \
) \
SELECT * FROM data) TO 'yourClientPath/output.csv' CSV HEADER;"

cat yourClientPath/output.csv

val1,val2
1,2

更新

如提供的示例,在终端的客户端计算机上,您需要运行以下脚本,其中包含您的绝对路径mycsv.csv

psql -h host -U username -d db -c "\COPY ( \
select month,count(*) as distinct_Count_month \
from \
  ( \
    select UNIQUE_MEM_ID,to_char(transaction_date, 'YYYY-MM') as month \
    FROM yi_fourmpanel.card_panel WHERE COBRAND_ID = '10006164' \
    group by UNIQUE_MEM_ID,to_char(transaction_date, 'YYYY-MM') \
  ) a \
group by month) TO 'path/mycsv.csv' WITH CSV HEADER;"
于 2016-02-03T23:49:55.057 回答