2014-12-03 47 views
0

我在SQL中創建了一個函數,用於計算獲取位置ID的函數的LocationIDS數量,並返回TABLE中存在該位置ID的次數。計算SQL中每一行的值的數量

我的問題是,當我打電話給我的存儲過程,函數 - 它顯示的是它的每一行,而不是顯示一列

比方說,例如在我的表:

LocationID NumberofshippingLocation 
------------------------------------ 
    48     2 
    48     2 
    52     1 

取而代之的合併所顯示兩次,一個

LocationID NumberofshippingLocation 
------------------------------------- 
    48     2  
    52     1 

查詢的那些:

-- Select [dbo].[fnGetNumberOfShippingLocations](52) 

ALTER FUNCTION [dbo].[fnGetNumberOfShippingLocations](@ShippingLocaitonID Int) 
RETURNS VarChar(50) 
AS 
BEGIN 
    Declare @rValue INT 

    Select @rValue = COUNT(*) 
    From GSACPeopleBadgeRequest 
    Where ShippedLocationID = @ShippingLocaitonID 

    Return @rValue 
END 

從我的存儲過程的調用是這樣的:

[dbo].[fnGetNumberOfShippingLocations](PBR.ShippedLocationID) AS 'NumberOfShippingLocation' 
+0

你嘗試SELECT DISTINCT? – JayHach 2014-12-03 19:16:07

+0

您的源表中已包含運送地點的數量? – Khan 2014-12-03 19:19:29

回答

1

必須使用GROUP BY子句。

此功能可統計記錄每ShippedLocationID數(結果= 2,對於ID = 48):

SELECT 
    @rValue = COUNT(*) 
FROM 
    GSACPeopleBadgeRequest 
GROUP BY 
    ShippedLocationID 
WHERE 
    ShippedLocationID = @ShippingLocationID 

如果你需要的總和,而不是記錄的只是數量,做到這一點(結果= 4,爲ID = 48):

SELECT 
    @rValue = SUM(NumberofshippingLocation) 
FROM 
    GSACPeopleBadgeRequest 
GROUP BY 
    ShippedLocationID 
WHERE 
    ShippedLocationID = @ShippingLocationID