行条件

时间:2015-10-08 06:47:12

标签: c# sql

SQL server 2008。 我有桌子:

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

那么,我想要总和有条件的行吗?

1 个答案:

答案 0 :(得分:0)

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

- 将COndition拆分为多行ID - 将该数据存入临时表 - 例如。 - 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'

代码未编译..根据需要制作chages ...