我有一个SQL查询,可以获得不同公司的工作数,毛重等。
我想在底部添加另一行来计算每列的总数,即作业列的总数为267.如何为总计添加额外的行?
SQL查询:
select
c.Name,
COUNT(distinct jn.ID) as Jobs,
SUM(jn.ActualWeight) as GrossWt,
SUM(jpc.AdvisedQty) AS Units_In,
SUM(jpd.AdvisedQty) AS Units_Out
FROM customer c
LEFT JOIN job_new jn ON jn.JobOwnerID = c.ID
LEFT JOIN job_pieces jp ON jp.JobID = jn.ID
LEFT JOIN job_pieces jpc ON jpc.JobID = jn.ID AND jn.CollectMemberID = jn.JobOwnerID
LEFT JOIN job_pieces jpd ON jpd.JobID = jn.ID AND jn.DeliverMemberID = jn.JobOwnerID
WHERE jn.IsActive = 1 GROUP BY jn.JobOwnerID
答案 0 :(得分:4)
您正在寻找GROUP BY
修饰符WITH ROLLUP
:
select c.Name,
COUNT(distinct jn.ID) as Jobs,
SUM(jn.ActualWeight) as GrossWt,
SUM(jpc.AdvisedQty) AS Units_In,
SUM(jpd.AdvisedQty) AS Units_Out
FROM customer c LEFT JOIN
job_new jn
ON jn.JobOwnerID = c.ID LEFT JOIN
job_pieces jp
ON jp.JobID = jn.ID LEFT JOIN
job_pieces jpc
ON jpc.JobID = jn.ID AND jn.CollectMemberID = jn.JobOwnerID LEFT JOIN
job_pieces jpd
ON jpd.JobID = jn.ID AND jn.DeliverMemberID = jn.JobOwnerID
WHERE jn.IsActive = 1
GROUP BY c.Name WITH ROLLUP;
注意:我还更改了GROUP BY
密钥有两个原因。首先,它确实应该匹配SELECT
中使用的列。其次,您使用的是LEFT JOIN
ed表中的值,因此值可能为NULL
。这通常是不受欢迎的。