简体   繁体   中英

SQL sum row with condition id of row

SQL server 2008. I have table:

ID         note       valueA        valueB     isCondition    condition
1          SumA         ?              ?         True          2+3+4
2          A.1          5              6         False
3          A.2          5              6         False
4          A.3          5              6         False
5          SumB         ?              ?         True          2+3
6          B.1          ?              ?         False

So, I want sum Rows that is has conditions?

CREATE TABLE #tmp (id int,splitdata int)

CREATE FUNCTION [dbo].[fnSplitdata] 
( 
    @string NVARCHAR(MAX), 
    @delimiter CHAR(1) ,
    @CurrentId int
) 
RETURNS @output TABLE(splitdata NVARCHAR(MAX) 
) 
BEGIN 
    DECLARE @start INT, @end INT 
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string) 
    WHILE @start < LEN(@string) + 1 BEGIN 
        IF @end = 0  
            SET @end = LEN(@string) + 1

        INSERT INTO #tmp  VALUES(CurrentId,SUBSTRING(@string, @start, @end - @start)) 
        SET @start = @end + 1 
        SET @end = CHARINDEX(@delimiter, @string, @start)

    END 
    RETURN 
END

--------------------------------------------------------------

SELECT ID from TableName as a CROSS APPLY dbo.fnSplitdata(a.Condition,'+',a.ID) as b

--Split COndition into multiple rows with ID --Taking that data into temporary table --eg -- 1 2 -- 1 3

update T1 set a.ValueA=(select sum(ValueA) from TableName join #tmp on TableName.ID=#tmp.splitdata and T1.ID=#tmp.id) from TableName T1 where IsCOndition=1 and Note='SumA'

update T1 set a.ValueA=(select sum(ValueB) from TableName join #tmp on TableName.ID=#tmp.splitdata and T1.ID=#tmp.id) from TableName T1 where IsCOndition=1 and Note='SumB'

Code is not compiled..make the chages as required...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM