简体   繁体   English

如何将查询结果添加到 SQL 中的表中?

[英]How to add query results to table in SQL?

I am trying to add the results of a query to an existing table, dependent on the values of an existing column.我正在尝试将查询结果添加到现有表中,具体取决于现有列的值。 For example, using the table below例如,使用下表

Store店铺 Sales销售量 Weekday平日
10 10 11000 11000 Weekday平日
11 11 5000 5000 Weekday平日
12 12 8000 8000 Weekday平日
10 10 19000 19000 Weekend周末
11 11 20000 20000 Weekend周末
12 12 5000 5000 Weekend周末

I want the averages per store and weekday which I can get using the following:我想要每个商店和工作日的平均值,我可以使用以下方法获得:

SELECT AVG(Sales) AS weekday_avg, store
FROM store_sales
WHERE Weekday = 'Weekday'
GROUP BY store;

But then I'd like to add these results to the same table and store in a column named 'weekday_avg'.但后来我想将这些结果添加到同一个表中并存储在名为“weekday_avg”的列中。

I've tried the following, and while I don't get an error, the column doesn't have any values added:我尝试了以下方法,虽然我没有收到错误,但该列没有添加任何值:

ALTER TABLE store_sales ADD COLUMN weekday_avg numeric;
UPDATE store_sales SET weekday_avg = (
    SELECT AVG(Sales) AS weekday_avg
    FROM store_sales
    WHERE Weekday = 'Weekday'
    GROUP BY store
);

I know this probably isn't best database practice, but I'm working with what has been provided and all I need is to end up with a table with columns for averages per store / weekday type that I can export into R for further analysis.我知道这可能不是最佳数据库实践,但我正在使用已提供的内容,我所需要的只是得到一个表,其中包含每个商店/工作日类型的平均值列,我可以将其导出到 R 以进行进一步分析.

Many thanks in advance!提前谢谢了!

Don't store the values.不要存储值。 They are easily calculated on the fly:它们很容易即时计算:

select ss.*,
       avg(sales) over (partition by store, weekday) as weekday_avg_sales
from store_sales ss;

Perhaps if you have a really big table, you might want to store the summary values.也许如果您有一个非常大的表,您可能想要存储汇总值。 But even so, I would recommend a second table for the summaries and joins.但即便如此,我还是会推荐第二张表用于汇总和连接。 With indexes, that would be much more efficient.使用索引,这将更有效率。

Note that calculating the data on the fly means that it is always up-to-date when existing data is updated or new data is inserted.请注意,动态计算数据意味着在更新现有数据或插入新数据时它始终是最新的。

As mentioned in other answer, don't store calculated values in table.如其他答案所述,不要将计算值存储在表中。

But if you want to know how it can be done, then one of the options is to use the corelated query as follows:但是,如果您想知道如何做到这一点,那么其中一种选择是使用相关查询,如下所示:

UPDATE store_sales s SET s.weekday_avg = (
    SELECT AVG(ss.Sales) AS weekday_avg
    FROM store_sales ss
    WHERE s.Weekday = ss.weekday
      And ss.store=s.store
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM