我有三个要与聚合函数进行内部连接并按分组的表。我的两个时间表都有一个外键,该外键引用空格表的ID。这是我的数据:
FROM gcr.io/google-appengine/openjdk:8
# Set locale to UTF-8
ENV LANG C.UTF-8
ENV LC_ALL C.UTF-8
# Install CloudProxy
ADD https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 ./cloud_sql_proxy
RUN chmod +x ./cloud_sql_proxy
#Download the latest version of Metabase
ADD http://downloads.metabase.com/v0.32.8/metabase.jar ./metabase.jar
CMD nohup ./cloud_sql_proxy -instances=$METABASE_SQL_INSTANCE=tcp:$MB_DB_PORT & java -jar /startup/metabase.jar
我希望我的输出数据看起来像这样(两个表中的时间合并为具有start和end属性的时间数组):
Spaces
id address
1 'Address 1, city, state, zip'
2 'Address 2, city, state, zip'
3 'Address 3, city, state, zip'
4 'Address 4, city, state, zip'
5 'Address 5, city, state, zip'
Times1
id1 spaces_id start end
1 1 '10am' '1pm'
2 1 '11am' '7pm'
3 1 '1am' '1pm'
4 2 '10am' '9pm'
5 2 '8am' '1pm'
Times2
id2 spaces_id start end
1 1 '10am' '1pm'
2 1 '11am' '7pm'
3 1 '1am' '1pm'
4 2 '10am' '9pm'
5 2 '8am' '1pm'
我已通过以下查询成功地将此数据与空格表和一个时间表合并:
Combined
id address times
1 'Address 1, city, state, zip' [{start: '10am', end: '1pm'}, {start: '11am', end: '7pm'}, ...]
2 'Address 2, city, state, zip' [{start: '10am', end: '9pm'}, {start: '8am', end: '1pm'}, ...]
3 'Address 3, city, state, zip' [...]
4 'Address 4, city, state, zip' [...]
5 'Address 5, city, state, zip' [...]
答案 0 :(得分:0)
您的结构和编写的查询之间存在一些不一致之处,因此我作了一些假设。因此,您可能需要调整查询。
SELECT
s.id,
s.address,
COALESCE(json_agg(d.json) filter (WHERE d.json IS NOT NULL), '[]')
FROM spaces s
LEFT JOIN (
SELECT
spaces_id,
json_build_object('start', start, 'end', "end") AS json
FROM (
SELECT * FROM times1
UNION ALL
SELECT * FROM times2
) t
) d ON d.spaces_id = s.id
GROUP BY s.id, s.address;
说明:
第一步,我们通过合并两个时间表来构建数据集d
,以便获得一个空间ID和所需的JSON对象。
然后选择空格,并在数据集d
上方左连接。对于d
中没有任何数据的空格,我们不想使用json_agg
,这将导致[null]
。相反,我们将那些过滤掉,这将导致null
。为了防止null
,我们COALESCE
使用一个空的JSON数组。