0

我正在尝试执行一个Select语句,该语句包含数据库中的多个表,并且其中添加了计算的计数列。我在要使用CASE语句的地方添加另一个计算列时遇到问题。

我的代码如下所示:

SELECT     
    Customers.FirstName, Customers.LastName, Customers.PrivateNumber, 
    Branches.Name, Pawns.ID, Pawns.StartDate, Pawns.FinishDate, 
    Items.Name, Items.Mass, Items.Quantity, Pawns.CurrentSum, 
    Transactions.[Percent], Currencies.Name as Currency,
    COUNT(1) OVER (PARTITION BY Pawns.ID) AS Cnt, 
    NewDistrPrcnt = (CASE WHEN COUNT(1) OVER (PARTITION BY Pawns.ID) > '1' 
                    THEN Items.Mass/SUM(Transactions.[Percent])*Transactions.[Percent] 
                    Else Transactions.[Percent] End)  
FROM         
    Customers 
INNER JOIN
    Pawns ON Customers.ID = Pawns.CustomerID 
INNER JOIN
    Items ON Pawns.ID = Items.PawnID 
INNER JOIN
    Branches ON Pawns.BranchID = Branches.ID AND Pawns.LocationID = Branches.ID 
INNER JOIN
    PawnTypes ON Pawns.PawnTypeID = PawnTypes.ID 
INNER JOIN
    Currencies ON PawnTypes.CurrencyID = Currencies.ID 
LEFT OUTER JOIN
    Transactions ON Pawns.ID = Transactions.PawnID AND Pawns.FinishDate = Transactions.Date
WHERE     
    (Pawns.StatusID = 6) AND (Pawns.FinishDate BETWEEN '15Oct2013' AND '23Oct2013')
ORDER BY 
    Pawns.ID, Branches.Name, Pawns.FinishDate DESC

当我尝试运行查询时返回以下错误:

消息 8120,级别 16,状态 1,行 1
列 'Customers.FirstName' 在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。

谁能帮我解决这个问题?

4

1 回答 1

0

问题在于 .SUM(Transactions.[Percent])将其替换为窗口函数为 :(SUM(Transactions.[Percent]) over ())并尝试如下:

SELECT     
    Customers.FirstName, Customers.LastName, Customers.PrivateNumber, 
    Branches.Name, Pawns.ID, Pawns.StartDate, Pawns.FinishDate, 
    Items.Name, Items.Mass, Items.Quantity, Pawns.CurrentSum, 
    Transactions.[Percent], Currencies.Name as Currency,
    COUNT(1) OVER (PARTITION BY Pawns.ID) AS Cnt 
    ,NewDistrPrcnt = (CASE WHEN COUNT(1) OVER (PARTITION BY Pawns.ID) > '1' 
                          THEN Items.Mass/(SUM(Transactions.[Percent]) over ())*Transactions.[Percent] 
                          Else Transactions.[Percent] End)  
FROM         
    Customers 
INNER JOIN
    Pawns ON Customers.ID = Pawns.CustomerID 
INNER JOIN
    Items ON Pawns.ID = Items.PawnID 
INNER JOIN
    Branches ON Pawns.BranchID = Branches.ID AND Pawns.LocationID = Branches.ID 
INNER JOIN
    PawnTypes ON Pawns.PawnTypeID = PawnTypes.ID 
INNER JOIN
    Currencies ON PawnTypes.CurrencyID = Currencies.ID 
LEFT OUTER JOIN
    Transactions ON Pawns.ID = Transactions.PawnID AND Pawns.FinishDate = Transactions.[Date]
WHERE     
    (Pawns.StatusID = 6) AND (Pawns.FinishDate BETWEEN '15Oct2013' AND '23Oct2013')
ORDER BY 
    Pawns.ID, Branches.Name, Pawns.FinishDate DESC
于 2013-10-24T09:28:30.840 回答