简体   繁体   English

如何使用 sql-window 函数在 SQL 中创建计算列?

[英]How to create calculated columns in SQL with sql-window functions?

So I am working on this solution that involves fetching input of 3 columns say 'Year', 'Month' and 'Spend' and use them to create another column 'Year Total' using logic that imitates SQL-window functions.所以我正在研究这个解决方案,它涉及获取 3 列的输入,比如“年”、“月”和“花费”,并使用它们使用模仿 SQL 窗口函数的逻辑创建另一列“年总计”。 For example, I need the following table given first three columns are editable,例如,我需要下表,因为前三列是可编辑的,

|------------|-------|--------|----------|
|   Year     |Month  |  Spend |Year Total|
|------------|-------|--------|----------|
|    2018    |   Jan |  10    |   55     |
|    2018    |   Feb |  20    |   55     |
|    2018    |   Oct |  25    |   55     |
|    2019    |   Jan |  15    |   120    |
|    2019    |   Aug |  60    |   120    |
|    2019    |   Nov |  45    |   120    |
|------------|-------|--------|----------|

But calculating this in the frontend and on the fly is making the solution very slow.但是在前端和动态计算这个会使解决方案变得非常缓慢。 Hence I am trying to move this calculation to the backend in the SQL table using calculated columns.因此,我试图使用计算列将此计算移动到 SQL 表中的后端。 Basically, data will be written to the backend(SQL), columns calculated and re-read to show in frontend.基本上,数据将写入后端(SQL),计算列并重新读取以显示在前端。

I have looked around a bit, only to find that windows functions cannot be used in calculated columns in SQL.我环顾了一下,才发现windows函数不能用在SQL的计算列中。 Also, note that stored procedures are not allowed in the solution.请注意,解决方案中不允许使用存储过程。

Can anyone suggest how to do this, or even if this is possible at all?任何人都可以建议如何做到这一点,或者即使这是可能的?

Note that frontend is Powerapps/Power BI请注意,前端是 Powerapps/Power BI

'using logic that imitates SQL-window functions' why? “使用模仿 SQL 窗口函数的逻辑”为什么?

You just need a join to a sub query which groups by year.您只需要加入按年份分组的子查询。

select t.* , s.sumspend
from <table> t
join (select year, sum(spend) sumspend from <table> group by year) s
on s.year = t.year;

Use a view:使用视图:

create view v_t as
    select t.* ,
           sum(spend) over (partition by year) as year_spend
    from t;

Window functions are not allowed in generated columns.生成的列中不允许使用窗口函数。

SQL Server allows window functions in updatable views, so you will be able to modify the other columns. SQL Server 允许可更新视图中的窗口函数,因此您将能够修改其他列。 You will need to reload the table whenever a change is made, to get the updated data.每当发生更改时,您都需要重新加载表,以获取更新的数据。

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

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