I'm writing a query which result will be displayed as dashboard on redash. The query is basically a sum of several columns of table within a specific time range:
我正在编写一个查询,结果将在redash上显示为仪表板。查询基本上是特定时间范围内的几列表的总和:
SELECT
sum(col_A),
sum(col_B),
sum(col_C)
FROM
table_X
WHERE
timestamp > '2018-01-01'
AND timestamp < '2018-02-01'
The result is something like this:
结果是这样的:
col_A col_B col_C
123 456 789
However, to render the dasboard on redash properly, I need the result in long format:
但是,要正确渲染redboard,我需要长格式的结果:
column sum
col_A 123
col_B 456
col_C 789
How can I cast the result from wide to long format?
如何将结果从长格式转换为长格式?
1 个解决方案
#1
3
A simple way is to use union all
:
一个简单的方法是使用union all:
SELECT sum(col_A) FROM table_X WHERE timestamp > '2018-01-01' AND timestamp < '2018-02-01'
UNION ALL
SELECT sum(col_B) FROM table_X WHERE timestamp > '2018-01-01' AND timestamp < '2018-02-01'
UNION ALL
SELECT sum(col_C) FROM table_X WHERE timestamp > '2018-01-01' AND timestamp < '2018-02-01';
You may need to be careful about the ordering. I would include a second column specifying which is being aggregated.
您可能需要注意订购。我将包括第二列,指定正在聚合的列。
Three separate queries is not quite as bad as it sounds. Redshift is a columnar database, so only the columns references should be read.
三个单独的查询并不像听起来那么糟糕。 Redshift是一个柱状数据库,因此只应读取列引用。
#1
3
A simple way is to use union all
:
一个简单的方法是使用union all:
SELECT sum(col_A) FROM table_X WHERE timestamp > '2018-01-01' AND timestamp < '2018-02-01'
UNION ALL
SELECT sum(col_B) FROM table_X WHERE timestamp > '2018-01-01' AND timestamp < '2018-02-01'
UNION ALL
SELECT sum(col_C) FROM table_X WHERE timestamp > '2018-01-01' AND timestamp < '2018-02-01';
You may need to be careful about the ordering. I would include a second column specifying which is being aggregated.
您可能需要注意订购。我将包括第二列,指定正在聚合的列。
Three separate queries is not quite as bad as it sounds. Redshift is a columnar database, so only the columns references should be read.
三个单独的查询并不像听起来那么糟糕。 Redshift是一个柱状数据库,因此只应读取列引用。