[英]Apply aggregate function to certain columns using SQL in Apache Druid
I have a table like this我有一张这样的桌子
----------------------
code sales goal
----------------------
b 7 20
b 12 20
a 9 15
c 4 3
a 4 15
And I want to perform an agg function to group by a sum only on 'sales' column, because 'goal' column is common to a given value in 'code' column to get something more like this而且我想执行 agg function 以仅在“销售”列上按总和进行分组,因为“目标”列对于“代码”列中的给定值是通用的以获得更多类似的东西
---------------------------------
code total goal
---------------------------------
b 19 20
a 13 15
c 4 3
Is there a way to perform something like this?有没有办法执行这样的事情?
SELECT code, SUM(sales) AS total, goal FROM such_table GROUP BY code
To then operate the columns to achieve the following future operations:然后操作这些列以实现以下未来操作:
------------------------------------------------------
code sum(sales) intact(goal) achvd(100*sum/goal)
------------------------------------------------------
b 19 20 95
a 13 15 86.6
c 4 3 133.3
Either include goal
in the group by
:将
goal
包括在group by
:
SELECT code, SUM(sales) AS total, goal, SUM(sales) * 1.0 / goal as ratio
FROM such_table
GROUP BY code, goal;
Or make it the argument to an aggregation function:或者将其作为聚合 function 的参数:
SELECT code, SUM(sales) AS total, MAX(goal) as goal,
SUM(sales) * 1.0 / MAX(goal) as ratio
FROM such_table
GROUP BY code;
If your data is actually structured this way, you have a problem with your data model.如果您的数据实际上是这样构造的,那么您的数据 model 就有问题。 The
goal
should not be repeated on each row.不应在每一行上重复
goal
。 You should have one table with one row per code
and that table should have the goal
.您应该有一个表,每个
code
一行,并且该表应该有goal
。 Then this table can just contain the sales.那么这个表可以只包含销售额。
Thank you all who contributed to this answer, I wanted to post the solution I use by reading you and surfing the web.感谢所有为这个答案做出贡献的人,我想通过阅读您和浏览 web 来发布我使用的解决方案。
Given the table such_table
:给定表
such_table
:
----------------------
code sales goal
----------------------
b 7 20
b 12 20
a 9 15
b 2 20
c 4 3
a 4 15
When applying the following query:应用以下查询时:
SELECT
code,
SUM(sales) AS total,
goal
FROM such_table
GROUP BY code, goal;
Results in the next table:下表中的结果:
---------------------
code total goal
---------------------
b 19 20
a 13 15
c 4 3
Thus in order to display desired results, next query is used:因此,为了显示所需的结果,使用下一个查询:
SELECT
code,
SUM(sales) AS total,
goal,
100 * (SUM(sales) / goal) AS prc_of_goal
FROM such_table
GROUP BY code, goal;
Resulting in the following:结果如下:
-----------------------------------
code total goal prc_of_goal
-----------------------------------
b 19 20 95
a 13 15 86.67
c 4 3 133.33
Which is what I was looking for这就是我要找的
Thank you all谢谢你们
:D :D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.