2015-11-20 112 views
1

我有如下SQL查詢:在列總和逗號分隔字符串中使用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); 

但不知道這能我的查詢裏面執行。任何建議?

回答

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 
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