[英]SQL sum row with condition id of row
SQL server 2008. I have table: 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
So, I want sum Rows that is has conditions?所以,我想要有条件的 sum Rows?
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 --将条件拆分为具有 ID 的多行 --将该数据放入临时表 --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...代码未编译...根据需要进行更改...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.