开发者

SQL Server - sum comma separated value from a column

开发者 https://www.devze.com 2022-12-26 16:42 出处:网络
There is a column in database which contains comma separated values like: 开发者_Go百科0.00,12.45,14.33 and so on.

There is a column in database which contains comma separated values like: 开发者_Go百科0.00,12.45,14.33 and so on.

I need to sum this inside a stored procedure. One way which I can think of is to split and convert it into a table using a function and then sum it.

Any other ideas?


Using Sql Server 2005+ CTE you can create a recursive select, something like

DECLARE @Table TABLE(
        ID INT,
        Vals VARCHAR(100)
)

INSERT INTO @Table SELECT 1, '0.00,12.45,14.33'
INSERT INTO @Table SELECT 2, '1,2,3,4'

;WITH ValList AS(
        SELECT  ID,
                CAST(LEFT(Vals,PATINDEX('%,%', Vals) - 1) AS FLOAT) Val,
                RIGHT(Vals,LEN(Vals) - PATINDEX('%,%', Vals)) Remainder
        FROM    @Table
        UNION ALL
        SELECT  ID,
                CAST(LEFT(Remainder,CASE WHEN PATINDEX('%,%', Remainder) = 0 THEN LEN(Remainder) ELSE PATINDEX('%,%', Remainder) - 1 END) AS FLOAT) Val,
                RIGHT(Remainder,CASE WHEN PATINDEX('%,%', Remainder) = 0 THEN 0 ELSE LEN(Remainder) - PATINDEX('%,%', Remainder) END) Remainder
        FROM    ValList
        WHERE   LEN(Remainder) > 0

)
SELECT  ID,
        SUM(Val)
FROM    ValList
GROUP BY ID

OUTPUT

ID          Total
----------- ----------------------
1           26.78
2           10


within a function you could try something like this, totally unsure if it will work tho!

CREATE FUNCTION ufn_sum_csv(@string varchar(100))
RETURNS @result int
AS BEGIN
EXEC 'SELECT @result = ' + REPLACE(@string,',','+')
RETURN

Can't try it out on this comp.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号