我有一个包含3个属性的表:
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 :(得分:1)
SELECT <Column Names>
FROM <Table Name>
UNION ALL
SELECT NULL,SUM(<Column name>),null,sum(<RunningTotal or AnyTotal>)
FROM <Table Name>
答案 1 :(得分:1)
如果您确实在[Submission]表中有[TotalNumberOfPublishedAuthors]和[TotalNumberOfAuthors]的列,那么就不需要加入任何其他表。只需执行查询中已有的总和,但不需要进一步的表格。
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 |