如何使用子查询设置计算列

How to set a calculated column using a subquery

我有一个 table,我想向其中添加一个计算列。我想将其设置为的查询比标准算术运算更复杂,我不确定如何使用查询设置计算列。我试图使用 ALTER TABLE 语句:

    ALTER TABLE shareholder.Amount
ADD CalculatedAmount As 
(SELECT sum(Amount) FROM shareholder.TransactionInput T 
                    WHERE T.ShareClassLabel = Amount.ShareClassLabel
                    AND T.ValuationDate < Amount.NAVDate
                    GROUP BY T.ShareClassLabel)

但这会导致错误:'Subqueries are not allowed in this context. Only scalar expressions are allowed'。 我知道子查询本身在对它自己进行测试后可以正常工作,所以这只是解决如何将计算列设置为它的结果的问题。

谢谢! (我正在使用 SQL Server 2014 Management Studio)

不可能有带有子查询的计算列,

A computed column is computed from an expression that can use other columns in the same table.

所以不可能有一个查询,但你可以使用像

这样的表达式
ColumnA-ColumnB+ColumnC

相反,您可以将其转换为视图并在那里计算列值

像这样

CREATE VIEW MyComputedvIEW
AS
SELECT
  *,
  CalculatedAmount = (SELECT sum(Amount) FROM shareholder.TransactionInput T 
                    WHERE T.ShareClassLabel = Amount.ShareClassLabel
                    AND T.ValuationDate < Amount.NAVDate
                    GROUP BY T.ShareClassLabel)
FROM YourTable

可以通过一个小技巧(UDF)添加子查询,参见我的示例([ChildCount] 字段):

CREATE TABLE [wp].[StorageData](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](200) NOT NULL,
    [StorageHid] [hierarchyid] NOT NULL,
    [StoragePath]  AS ([StorageHid].[ToString]()),
    [StorageLevel]  AS ([StorageHid].[GetLevel]()),
    [StorageParentHid]  AS ([StorageHid].[GetAncestor]((1))),
    [StorageParent]  AS ([StorageHid].[GetAncestor]((1)).ToString()),
    [ChildCount]  AS ([wp].[GetStorageDataChildItemCount]([StorageHid].[ToString]()))
)

CREATE FUNCTION [wp].[GetStorageDataChildItemCount]
(
    @storagePath NVARCHAR(4000)
)
RETURNS INT
AS
BEGIN

    DECLARE @ret INT = 0;
    SET @ret = (SELECT COUNT(ID) FROM [wp].[StorageData] R WHERE R.StorageParent = @storagePath)
    RETURN @ret;

END