计算列

时间:2019-01-14 18:00:47

标签: sql tsql

我有2个表(用户和报告)。用户存储一些用户信息,包括其ID。报告存储系统中可用报告的列表,其中“所有者”字段显示哪个用户拥有该报告。我有一个视图,其中包含用户表中的某些列。我想在视图中增加一个计算列,以显示用户拥有多少个报告。

类似: SELECT所有者,count(*)为ReportsOwned 来自报告 GROUP BY所有者;

这是视图:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [dbo].[Users_SPO] AS
SELECT DisplayName AS Name,
       ManagedBy AS [Managed By],
       CanBeDeleted AS [Can Be Deleted],
       PrimarySmtpAddress AS Email,
       TeamsEnabled AS [Team Enabled],
       NumberOfChats AS Chats,
       NumberOfConversations AS Conversations,
       SPOActivity AS [SPO Activity],
       SPOStatus AS [SPO Status],
       Notes AS Description,
       WhenCreated AS [Creation Date],
       WhenChanged AS [Change Date],
       ExternalDirectoryObjectId
  FROM dbo.Users
GO

1 个答案:

答案 0 :(得分:0)

这是一个猜测,因为您没有定义两个表或它们之间的任何链接。我希望你能在某个地方有一个田野。

CREATE VIEW [dbo].[Users_SPO] AS SELECT DisplayName AS Name, ManagedBy AS [Managed By], CanBeDeleted AS [Can Be Deleted], PrimarySmtpAddress AS Email, TeamsEnabled AS [Team Enabled], NumberOfChats AS Chats, NumberOfConversations AS Conversations, SPOActivity AS [SPO Activity], SPOStatus AS [SPO Status], Notes AS Description, WhenCreated AS [Creation Date], WhenChanged AS [Change Date], ExternalDirectoryObjectId, (SELECT count(*) FROM Reports rp where rp.owner = displayname) as ReportsOwned FROM dbo.Users GO