Sum Comma使用SQL在列中分隔字符串

时间:2015-11-20 05:07:56

标签: sql sql-server sql-server-2008

我有一个SQL查询,如下所示:

WITH mytable as
(
    SELECT 
        (CAST(CASE 
                 WHEN Quote_Value LIKE '-%' THEN N'0' 
                 WHEN Quote_Value = '' THEN N'0' 
                 ELSE REPLACE(REPLACE(Quote_Value,'$',''),',','+') 
              END as Decimal)) as q,
        DATEDIFF(week, '2015-10-06', date) AS WeekNumber
    FROM 
        Showroom_perf)  
SELECT
    WeekNumber,
    SUM(q) as [Quote Value]
FROM
    mytable
GROUP BY
    WeekNumber

Quote_Value也可以有一些逗号分隔值 - 如果是,则需要对逗号分隔值求和。

如果没有创建任何功能和/或表,我可以建议吗? 我看到的一个可能的解决方案是执行一个表达式:

declare @str nvarchar(max) = '23,12,12,32,43';
set @str = 'select '+replace(@str, ',', '+');
exec(@str);

但不确定这是否可以在我的查询中执行。有什么建议吗?

2 个答案:

答案 0 :(得分:0)

与CTE有关吗?

declare @str nvarchar(max) = '23|12|12|32|43';
declare @delimiter nvarchar(1) = '|';

;WITH SplitTable AS
(
    SELECT
        LEFT(@str,CHARINDEX(@delimiter,@str)-1) AS Part
            ,RIGHT(@str,LEN(@str)-CHARINDEX(@delimiter,@str)) AS Remainder
    UNION ALL
    SELECT
        LEFT(Remainder,CHARINDEX(@delimiter,Remainder)-1)
            ,RIGHT(Remainder,LEN(Remainder)-CHARINDEX(@delimiter,Remainder))
        FROM SplitTable
        WHERE Remainder IS NOT NULL AND CHARINDEX(@delimiter,Remainder)>0
    UNION ALL
    SELECT
        Remainder,null
        FROM SplitTable
        WHERE Remainder IS NOT NULL AND CHARINDEX(@delimiter,Remainder)=0
)
SELECT sum(convert(int,Part)) FROM SplitTable

答案 1 :(得分:0)

我现在有一个工作正在为我工​​作 - 但只是想知道这是否是正确的方式或是否有任何其他影响:

WITH mytable as(
SELECT 
    (CAST(CASE  WHEN Quote_Value LIKE '-%' THEN N'0' WHEN Quote_Value = '' THEN N'0' 
    ELSE CAST('<root><e>' + REPLACE(REPLACE(Quote_Value,'$',''),',','+') + '</e></root>' AS XML)
        .value('sum(/root/e) + count(/root/e) * 10', 'Decimal') END as Decimal)) as q,
    DATEDIFF(week, '2015-10-06', date) AS WeekNumber
    FROM Showroom_perf
)  
Select 
WeekNumber,
SUM(q) as [Quote Value]
from mytable
GROUP BY
WeekNumber