Sql-Server
如何使用 JOIN 和 SUM 函式計算查詢返回列的總數?
我跑了以下查詢;
詢問:
SELECT j.jobId, j.productId, p.productUnitPrice FROM JobRequiredProducts J JOIN Product p ON p.productId = j.productId WHERE j.jobId = 1 ORDER BY j.jobId
並得到以下結果;
查詢結果:
jobId | productId | unitPrice _____________________________ 1 | 4 | 175.99 1 | 5 | 100.00 1 | 6 | 125.00
現在,我想計算所有的 unitPrice 以獲得總數。我期望的結果是;
預期結果:
jobId | productId | Total ____________________________ 1 | 4 | 175.99 1 | 5 | 100.00 1 | 6 | 125.00 null | null | 400.99
因此,下面是我嘗試過的查詢;
我試過的查詢:
SELECT j.jobId, j.productId, SUM(p.productUnitPrice) AS 'Total' FROM JobRequiredProducts J JOIN Product p ON p.productId = j.productId WHERE j.jobId = 1 GROUP BY j.jobId,j.productId WITH ROLLUP
但它沒有給我預期的結果,我哪裡出錯了,我必須做什麼才能得到預期的結果?
您也可以使用分組集
declare @JobRequiredProducts table (jobId int, productId int); declare @Product table(productId int, productUnitPrice decimal(8,2)) insert into @JobRequiredProducts(jobId,productId) values(1,4),(1,5),(1,6); insert into @Product(productId, productUnitPrice) values(4,175.99),(5 ,100.00),( 6 , 125.00) SELECT j.jobId, j.productId, SUM(p.productUnitPrice) AS 'Total' FROM @JobRequiredProducts J JOIN @Product p ON p.productId = j.productId WHERE j.jobId = 1 GROUP BY ROLLUP ((j.jobId, j.productId));
帶分組集
SELECT j.jobId, j.productId, SUM(p.productUnitPrice) AS 'Total' FROM @JobRequiredProducts J JOIN @Product p ON p.productId = j.productId WHERE j.jobId = 1 GROUP BY GROUPING SETS( (j.jobId, j.productId),());
輸出:
jobId productId Total 1 4 175.99 1 5 100.00 1 6 125.00 NULL NULL 400.99
dbfiddle在這裡