在带有count的sql Select语句中使用CASE

时间:2013-10-24 08:59:42

标签: sql sql-server case

我正在尝试执行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

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

  

Msg 8120,Level 16,State 1,Line 1
  列'Customers.FirstName'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分: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