计算SQL中每行的值数

时间:2014-12-03 19:11:29

标签: sql sql-server tsql stored-procedures

我在SQL中创建了一个函数,用于计算函数获取位置ID的LocationIDS数量,并返回TABLE中存在locationID的次数。

我的问题是当我在我的存储过程中调用该函数时 - 它是为每行显示它而不是显示一列

比如说,在我的表中:

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'

1 个答案:

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