2015-09-28 107 views
0

計算總我有3個屬性表:使用SQL查詢

Title   TotalNumberOfAuthors    TotalNumberOfPublishedAuthors 
A     3           1 
B     2           2 
C     4           2 
D     2           1 

我試圖創建一個顯示的TotalNumberOfPublishedAuthors之和爲TotalNumberOfNonPublishedAuthors總和是一個查詢(TotalNumberofAuthors - TotalNumberOfPublishedAuthors)..

這是我所生成的查詢,但不顯示預期的結果:

SELECT SUM(Submission.TotalNumberOfPublishedAuthors),   
     (SUM(Submission.TotalNumberOfAuthors) - SUM(Submission.TotalNumberOfPublishedAuthors)) AS Number_of_Non_Published_Authors 
FROM Submission INNER JOIN ((Faculty INNER JOIN School 
ON Faculty.FacultyID = School.[FacultyID]) INNER JOIN (Researcher INNER JOIN ResearcherSubmission 
ON Researcher.ResearcherID = ResearcherSubmission.ResearcherID) 
ON School.SchoolID = Researcher.SchoolID) 
ON Submission.SubmissionID = ResearcherSubmission.SubmissionID; 

這是我想要得到的結果:

TotalNumberofPublishedAuthors      TotalNumberofPublishedAuthors 
     6              5 
+0

你的問題很混亂。你說你有一張桌子,然後你用多個桌子顯示一個查詢。你可以用一些示例數據設置一個SQL小提琴嗎? –

+0

此外,它將有助於顯示正在返回的值,或者SQL只是不起作用? – MiguelH

+1

看着你已經使用過的查詢應該可以得到你所期望的結果。 'SUM(Submission.TotalNumberOfPublishedAuthors), (SUM(Submission.TotalNumberOfAuthors) - SUM(Submission.TotalNumberOfPublishedAuthors))' 但是按照你的結果是不同的,你會得到什麼? – Abhishek

回答

1
SELECT <Column Names> 
FROM <Table Name> 
UNION ALL 
SELECT NULL,SUM(<Column name>),null,sum(<RunningTotal or AnyTotal>) 
FROM <Table Name> 
1

如果你真的有表中的列[投稿]稱爲[TotalNumberOfPublishedAuthors]和[TotalNumberOfAuthors]如圖所示那麼就沒有必要加入任何其他表格。只需執行總和,因爲您已經在查詢中擁有它們,但沒有更多表格。

SQL Fiddle

的MS SQL Server 2014架構設置

CREATE TABLE Submission 
    ([Title] varchar(1), [TotalNumberOfAuthors] int, [TotalNumberOfPublishedAuthors] int) 
; 

INSERT INTO Submission 
    ([Title], [TotalNumberOfAuthors], [TotalNumberOfPublishedAuthors]) 
VALUES 
    ('A', 3, 1), 
    ('B', 2, 2), 
    ('C', 4, 2), 
    ('D', 2, 1) 
; 

查詢1

SELECT 
     SUM(Submission.TotalNumberOfPublishedAuthors) AS TotalNumberOfPublishedAuthors 
    , SUM(Submission.TotalNumberOfAuthors) 
    - SUM(Submission.TotalNumberOfPublishedAuthors) AS Number_of_Non_Published_Authors 
FROM Submission 

Results

| TotalNumberOfPublishedAuthors | Number_of_Non_Published_Authors | 
|-------------------------------|---------------------------------| 
|        6 |        5 |