在SQL查询中运行for循环

时间:2023-01-27 22:58:09

Suppose I had a table with the following structure:

假设我有一个具有以下结构的表:

income event, frequency, user

收入事件,频率,用户

and sample data like:

和样本数据如:

12,1,a 5,10,a 6,2,b

12,1,a 5,10,a 6,2,b

What would a sql query look like that loops across users, and sums each income event x frequency

sql查询会在用户之间循环,并对每个收入事件x频率求和

The output would look like:

输出看起来像:

a, 62 b,12

a,62 b,12

I am relatively new to sql so have little experience with group by functions, and am coming from an R background

我对sql相对较新,所以对于按功能分组的经验很少,而且我来自R背景

1 个解决方案

#1


3  

Your query would look like this:

您的查询将如下所示:

SELECT user, SUM([income event] * frequency) AS SumOfEvents FROM [tablename] GROUP BY user

When you GROUP BY a field, you are aggregating (e.g., SUM, COUNT) values for any of the other columns you SELECT by. You would just specify the columns you GROUP by.

当您对某个字段进行GROUP BY时,您将为SELECT所选的任何其他列聚合(例如,SUM,COUNT)值。您只需指定GROUP by的列。

So user would just be selected, then you'd take the SUM of the product of the other columns.

因此,只需选择用户,然后您将获取其他列的产品的SUM。

#1


3  

Your query would look like this:

您的查询将如下所示:

SELECT user, SUM([income event] * frequency) AS SumOfEvents FROM [tablename] GROUP BY user

When you GROUP BY a field, you are aggregating (e.g., SUM, COUNT) values for any of the other columns you SELECT by. You would just specify the columns you GROUP by.

当您对某个字段进行GROUP BY时,您将为SELECT所选的任何其他列聚合(例如,SUM,COUNT)值。您只需指定GROUP by的列。

So user would just be selected, then you'd take the SUM of the product of the other columns.

因此,只需选择用户,然后您将获取其他列的产品的SUM。