我的查询如下:
SELECT w.payload,
Count('payload') OVER () AS ROWCOUNT
FROM wholesale_confirmation.wholesale_order_confirmation w
WHERE w.delivery_date = COALESCE(NULL, w.delivery_date)
AND w.ship_to_location_id = COALESCE(NULL, w.ship_to_location_id)
AND w.order_raised_date = COALESCE(NULL, w.order_raised_date)
AND w.ship_from_location_id = COALESCE(NULL, w.ship_from_location_id)
LIMIT 10
OFFSET 0;
这给我的结果如下:
我想改为{"payload:"[payload1,payload2,payload3],"rowcount":n}
。
Postgres版 10.3 ,payload
数据类型为jsonb
答案 0 :(得分:4)
COALESCE(NULL, w.delivery_date)
归结为w.delivery_date
。
因此WHERE w.delivery_date = COALESCE(NULL, w.delivery_date)
归结为WHERE w.delivery_date IS NOT NULL
。
Count('payload') OVER () AS ROWCOUNT
只是说count(*) OVER () AS rowcount
的嘈杂方式,并返回结果的总行数。
您当前的查询,简化:
SELECT payload, count(*) OVER () AS rowcount
FROM wholesale_confirmation.wholesale_order_confirmation
WHERE delivery_date IS NOT NULL
AND ship_to_location_id IS NOT NULL
AND order_raised_date IS NOT NULL
AND ship_from_location_id IS NOT NULL
LIMIT 10;
获取更新后的问题中的JSON对象,包含一个JSON对象数组和总行数:
SELECT json_build_object('payload', jsonb_agg(payload), 'rowcount', min(rowcount))
FROM (
SELECT payload, count(*) OVER () AS rowcount
FROM wholesale_confirmation.wholesale_order_confirmation
WHERE delivery_date IS NOT NULL
AND ship_to_location_id IS NOT NULL
AND order_raised_date IS NOT NULL
AND ship_from_location_id IS NOT NULL
LIMIT 10
) sub;
如果您正在处理多个行,LIMIT
/ OFFSET
的效果会降低。考虑更复杂的分页技术:
答案 1 :(得分:1)
WITH foobar AS (
SELECT w.payload,
Count('payload') OVER () AS ROWCOUNT
FROM wholesale_confirmation.wholesale_order_confirmation w
WHERE w.delivery_date = COALESCE(NULL, w.delivery_date)
AND w.ship_to_location_id = COALESCE(NULL, w.ship_to_location_id)
AND w.order_raised_date = COALESCE(NULL, w.order_raised_date)
AND w.ship_from_location_id = COALESCE(NULL, w.ship_from_location_id)
LIMIT 10
OFFSET 0
)
SELECT
json_build_object('payload', payload, 'rowcount', rowcount)
FROM
foobar