我总是要从SQL服务器表中获取涉及子计算的内容,并且无法确定如何进行嵌套,任何帮助都会受到限制。
表格(注意:截至有用的数据)
PrintJob - ID,DEPT,CopyCount 有很多印记(注意它的副本数不同) 版本说明 - ID,JobId,CopyCount 有很多pageDatas PageData - ImprintID,Index,ImpressionCount
现在我需要获得每个DEPT (PrintJob.CopyCount *的总和(imprint.CopyCount *其总和(印记' s PageData.ImpressionCount)))()
因此,对于每个印记,需要将其所有页面数据的印象数总计,然后再加上印记的CopyCount。
然后可以针对每个PrintJob将每个印记的总和相加,以给出每个Printjob的印记副本数量,这样就可以乘以PrintJob.CopyCount来给出每个作业的印记总数。
然后可以将每个部门的每个打印作业相加,以给出我的最终结果表,但是如何在一个查询中有效地获得该效果呢?
示例数据
CREATE TABLE PrintJob
(
ID varchar(10),
DEPT varchar(10),
CopyCount int
);
CREATE TABLE Imprint
(
ID varchar(10),
JobId varchar(10),
CopyCount int
);
CREATE TABLE PageData
(
ImprintID varchar(10),
[Index] int,
ImpressionCount int
);
INSERT INTO PrintJob (ID, DEPT, CopyCount)
Values
('J1','D1',2),
('J2','D1',1),
('J3','D2',5),
('J4','D2',4)
;
INSERT INTO Imprint (ID, JobId, CopyCount)
Values
('I1','J1',1),
('I2','J1',2),
('I3','J2',1),
('I4','J3',2),
('I5','J4',2),
('I6','J4',2)
;
INSERT INTO PageData (ImprintID, [Index], ImpressionCount)
Values
('I1',1,1),
('I1',2,3),
('I1',3,1),
('I2',1,1),
('I3',1,1),
('I3',2,2),
('I4',1,1),
('I4',2,1),
('I5',1,1),
('I6',1,5)
;
答案 0 :(得分:0)
如果我是对的,你的意思是:
select j.DEPT, sum(j.CopyCount * i.SubCount) TotalCount
from PrintJob j
join (
select i.JobId, sum(i.CopyCount * p.ICountSum) SubCount
from Imprint i
join (
select ImprintID, SUM(ImpressionCount) ICountSum
from PageData
group by ImprintID) p on p.ImprintID= i.ID
group by i.JobId) i on i.JobId = j.ID
group by j.DEPT