简体   繁体   English

如何将列添加到现有表并计算值

[英]How to add column to an existing table and calculate the value

Table info:表信息:

在此处输入图像描述

I want to add new column and calculated the different of the alarmTime column with this code:我想添加新列并使用以下代码计算 alarmTime 列的不同:

ALTER TABLE [DIALinkDataCenter].[dbo].[DIAL_deviceHistoryAlarm] 
    ADD dif AS (DATEDIFF(HOUR, LAG((alarmTime)) OVER (ORDER BY (alarmTime)), (alarmTime)));

How to add the calculation on the table?如何在表格中添加计算? Because always there's error like this:因为总是有这样的错误:

Windowed functions can only appear in the SELECT or ORDER BY clauses.窗口函数只能出现在 SELECT 或 ORDER BY 子句中。

You are using the syntax for a generated virtual column that shows a calculated value ( ADD columnname AS expression ).您正在使用显示计算值的生成虚拟列的语法( ADD columnname AS expression )。

This, however, only works on values found in the same row.但是,这仅适用于在同一行中找到的值。 You cannot have a generated column that looks at other rows.您不能拥有查看其他行的生成列。

If you consider now to create a normal column and fill it with calculated values, this is something you shouldn't do.如果您现在考虑创建一个普通列并用计算值填充它,这是您不应该做的事情。 Don't store values redundantly.不要冗余地存储值。 You can always get the difference in an ad-hoc query.您始终可以在即席查询中获得差异。 If you store this redundantly instead, you will have to consider this in every insert, update, and delete.如果您改为冗余存储它,则必须在每次插入、更新和删除时都考虑到这一点。 And if at some time you find rows where the difference doesn't match the time values, which column holds the correct value then and which the incorrect one?如果在某个时候您发现差异与时间值不匹配的行,那么哪一列包含正确的值,哪一列包含不正确的值? alarmtime or dif?闹钟时间还是差异? You won't be able to tell.你将无法分辨。

What you can do instead is create a view for convenience:您可以做的是为方便起见创建一个视图:

create view v_dial_devicehistoryalarm as
select 
  dha.*,
  datediff(hour, lag(alarmtime) over (order by alarmtime), alarmtime) as dif
from dial_devicehistoryalarm dha;

Demo: https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=b7f9b5eef33e72955c7f135952ef55b5演示: https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=b7f9b5eef33e72955c7f135952ef55b5

Remember though, that your view will probably read and sort the whole table everytime you access it.但请记住,您的视图可能会在您每次访问它时读取整个表并对其进行排序。 If you query only a certain time range, it will be faster hence to calculate the differences in your query instead.如果您只查询某个时间范围,那么计算查询中的差异会更快。

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

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