2011-04-07 94 views
3

問候。幫助創建計算列(sql server 2008)

需要與此表上創建一個計算列一些幫助:

USE [ScienceWorksSummary] 

GO 

/****** Object: Table [dbo].[Authors_Articles] Script Date: 04/07/2011 10:38:55 ******/ 
SET ANSI_NULLS ON 
GO 

SET QUOTED_IDENTIFIER ON 
GO 

CREATE TABLE [dbo].[Authors_Articles](
    [IdAuthor] [int] NOT NULL, 
    [IdArticle] [int] NOT NULL, 
    [Part] [float] NULL, 
CONSTRAINT [PK_Authors_Articles] PRIMARY KEY CLUSTERED 
(
    [IdAuthor] ASC, 
    [IdArticle] ASC 
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
) ON [PRIMARY] 

GO 

計算列(部分)的關鍵是讓每個作者,即寫了同一篇文章的工作的一部分。因此,例如,如果idAuthor = 1,idArticle = 1且idAuthor = 2,idArticle = 1,則 ,那麼每個元素的Part必須爲0.5。

感謝您的幫助!

回答

3
CREATE TABLE [dbo].[Authors_Articles](
    [IdAuthor] [int] NOT NULL, 
    [IdArticle] [int] NOT NULL, 
CONSTRAINT [PK_Authors_Articles] PRIMARY KEY CLUSTERED 
(
    [IdAuthor] ASC, 
    [IdArticle] ASC 
)) 
GO 
create function dbo.calcPart(@IdArticle int) returns float as 
begin 
return (Select 1.0/count(*) from [Authors_Articles] where IdArticle = @IdArticle) 
end 
GO 
alter table Authors_Articles add Part as dbo.calcPart(IdArticle) 
+0

謝謝! :)將1.0/count(*)更改爲ROUND((1.0/count(*)),2)並且獲得了我需要的東西! – DeadDream 2011-04-07 08:31:46