
[英]Select returns empty result when injecting a variable in the query string
[英]psycopg returns empty query result when there is data
我正在尝试从下面的 postgressql 查询中获取记录。 它确实有数据,但是当我尝试用 psycopg 检索它时,奇怪的是它返回空。 它是否适用于 WITH 查询,或者我们只能使用 SELECT 代替? 任何输入将不胜感激,谢谢。
query = \
f""" WITH a AS (
SELECT "public"."table_a"."code",
"public"."table_a"."address", sum("public"."table_a"."amount") AS
"sum" FROM "public"."table_a" WHERE "public"."table_a"."address" <> 'KL' GROUP BY
"public"."table_a"."code", "public"."table_a"."address"),
c as (
WITH b AS (
SELECT address, code, count(*) as "total" FROM table_b where created_date between
((current_date + TIME '14:00:00.000+08:00') - interval '7 days') and ((
current_date + TIME '23:59:00.000+08:00') - interval '7 days') group by
address, code order by address, code)
select b.address, table_c.unit_code, table_c.name, sum(b.total *
table_c.amount) as "total" from table_c join b on table_c.code = b.code
group by table_c.unit_code, table_c.name, b.address
order by table_c.unit_code, b.address
)
SELECT a.address, a.code, (a.sum - c.total)::int as output
FROM a join c on a.code = c.unit_code
AND a.address = c.address
ORDER BY a.address, a.code
"""
conn = psycopg2.connect(**params)
cur = conn.cursor()
cur.execute(query)
rows = cur.fetchall()
for row in rows:
print(row)
我花了一整天的时间才意识到日志中的时间戳与预期的不同。 下面的查询有效(使用 WITH AS 和所有),只需要为我删除时区,因为我不需要它。 学习到教训了。 确保检查服务器时区以及是否需要转换。 希望这对将来的某人有所帮助。
WITH a AS (
SELECT "public"."table_a"."code",
"public"."table_a"."address", sum("public"."table_a"."amount") AS
"sum" FROM "public"."table_a" WHERE "public"."table_a"."address" <> 'KL' GROUP BY
"public"."table_a"."code", "public"."table_a"."address"),
c as (
WITH b AS (
SELECT address, code, count(*) as "total" FROM table_b where created_date between
((current_date + TIME '14:00:00.000') - interval '7 days') and ((
current_date + TIME '23:59:00.000') - interval '7 days') group by
address, code order by address, code)
select b.address, table_c.unit_code, table_c.name, sum(b.total *
table_c.amount) as "total" from table_c join b on table_c.code = b.code
group by table_c.unit_code, table_c.name, b.address
order by table_c.unit_code, b.address
)
SELECT a.address, a.code, (a.sum - c.total)::int as output
FROM a join c on a.code = c.unit_code
AND a.address = c.address
ORDER BY a.address, a.code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.