我们如何使用内连接对SQL中的列进行分组?

时间:2016-08-20 13:32:08

标签: sql sql-server sql-server-2008

我会附上截图,请看一下:

CLIK HERE TO VIEW PICTURE

在此我需要根据每个分支名称获得[LOCAL CURRENCY]的总和

SELECT 
    BR.BranchName [BRANCH NAME],
    PDS.ProductName [CURRENCY], 
    SUM(FCBD.Quantity) [QUANTITY],
    FCBD.BuyingRate [RATE],
    SUM(CONVERT(DECIMAL(12, 3), (FCBD.Quantity * FCBD.BuyingRate))) [LOCAL CURRENCY], 
    0 [TOTAL]
FROM 
    ALX_FCBuy FCB
INNER JOIN 
    ALX_FCBuyDetails  FCBD ON FCB.FCBuyID = FCBD.FCBuyID
INNER JOIN 
    ALX_Branches BR ON FCB.BranchID = BR.BranchID                   
INNER JOIN 
    ALX_Products PDS ON FCBD.ProductID = PDS.ProductID
GROUP BY 
    BR.BranchName, FCBD.ProductID, PDS.ProductName, FCBD.BuyingRate

2 个答案:

答案 0 :(得分:1)

如果您需要每个分支的总和,那么只需将其放在SELECTGROUP BY中:

SELECT BR.BranchName [BRANCH NAME],
        SUM(CONVERT(DECIMAL(12, 3), FCBD.Quantity * FCBD.BuyingRate)) [LOCAL CURRENCY], 
FROM ALX_FCBuy FCB INNER JOIN 
     ALX_FCBuyDetails FCBD
     ON FCB.FCBuyID = FCBD.FCBuyID INNER JOIN 
     ALX_Branches BR
     ON FCB.BranchID = BR.BranchID INNER JOIN 
     ALX_Products PDS
     ON FCBD.ProductID = PDS.ProductID
GROUP BY BR.BranchName;

如果您希望现有结果集中有附加列,则计算将使用窗口函数:

SELECT . . .
       SUM(SUM(CONVERT(DECIMAL(12, 3), FCBD.Quantity * FCBD.BuyingRate))) OVER (PARTITION BY BR.BranchName) as Total
. . .

答案 1 :(得分:1)

SELECT 
BR.BranchName [BRANCH NAME],
PDS.ProductName [CURRENCY], 
SUM(FCBD.Quantity) [QUANTITY],
FCBD.BuyingRate [RATE],
SUM(CONVERT(DECIMAL(12, 3), (FCBD.Quantity * FCBD.BuyingRate))) [LOCAL CURRENCY], 
SUM(SUM(CONVERT(DECIMAL(12, 3), FCBD.Quantity * FCBD.BuyingRate))) OVER (PARTITION BY BR.BranchName)  [TOTAL]
 FROM 
ALX_FCBuy FCB
 INNER JOIN 
ALX_FCBuyDetails  FCBD ON FCB.FCBuyID = FCBD.FCBuyID
 INNER JOIN 
ALX_Branches BR ON FCB.BranchID = BR.BranchID                   
 INNER JOIN 
ALX_Products PDS ON FCBD.ProductID = PDS.ProductID
 GROUP BY 
BR.BranchName, FCBD.ProductID, PDS.ProductName, FCBD.BuyingRate