count and remove individual values of a single column - sql-server

I have a table and the values like this
create table items_table(url varchar(max),counttotal_urls int,countduplicate_urls int,Unique_urls varchar(max),
countUnique_urls int)
insert into items_table(url) values('ht,ha,hb,ha|hc|hy')
insert into items_table(url) values('ht,hb,hb|hb|hx|hx')
insert into items_table(url) values('hz,hy,hx,hm|hm,hy')
insert into items_table(url) values('hz,hy,hx,hm|hm,hy')
I need to replace ,h with |h , for this I will use replace(url,',h','|h')
I need to count total_urls present by considering the separation '|'
I want to check or count how may duplicate url's are present
I want unique_urls to be updated in the Unique_url's column by removing the duplicates
Finally I want to count the Unique_urls which will be updated in another column
Desired output:

This is a bit complicated. But I tried to achieve it in Set based methodology.
Your Schema:
CREATE TABLE #items_table (
id INT identity
,url VARCHAR(max)
,counttotal_urls INT
,countduplicate_urls INT
,Unique_urls VARCHAR(max)
,countUnique_urls INT
)
INSERT INTO #items_table (url)
VALUES ('ht,ha,hb,ha|hc|hy')
INSERT INTO #items_table (url)
VALUES ('ht,hb,hb|hb|hx|hx')
INSERT INTO #items_table (url)
VALUES ('hz,hy,hx,hm|hm,hy')
INSERT INTO #items_table (url)
VALUES ('hy,hx,hm|hm,hy')
I have used several CTE's and XML methods
;WITH CTE
AS (
SELECT url
,REPLACE(',' + url, ',h', '|h') AS url2
,CAST('<M>'
+ REPLACE(REPLACE(',' + url, ',h', '|h'), '|', '</M><M>')
+ '</M>' AS XML) AS XML_FLD
FROM #items_table
)
,CTE2
AS (
SELECT url
,SUM(CASE
WHEN SUBSTRING(url2, number, 1) > '|'
THEN 1
ELSE 0
END) / 2 AS counttotal_urls
FROM CTE C
CROSS APPLY (
SELECT *
FROM master.dbo.spt_values
WHERE type = 'P'
AND number BETWEEN 1
AND LEN(C.url2)
) CA
GROUP BY url
)
,CTE3
AS (
SELECT C2.url
,C2.counttotal_urls
,SPLITS.ABC.value('.', 'varchar(MAX)') DUP_URLS
FROM CTE2 C2
INNER JOIN CTE C ON C2.url = C.url
CROSS APPLY C.XML_FLD.nodes('/M') AS SPLITS(ABC)
)
SELECT url
,counttotal_urls
,counttotal_urls - (COUNT(DISTINCT DUP_URLS) - 1) AS countduplicate_urls
,STUFF((
SELECT DISTINCT '|' + DUP_URLS
FROM CTE3 C
WHERE C3.url = C.url
FOR XML PATH('')
), 1, 1, '') AS Unique_urls
FROM CTE3 C3
GROUP BY url
,counttotal_urls
Result will be
+-------------------+-----------------+---------------------+-----------------+
| url | counttotal_urls | countduplicate_urls | Unique_urls |
+-------------------+-----------------+---------------------+-----------------+
| ht,ha,hb,ha|hc|hy | 6 | 1 | |ha|hb|hc|ht|hy |
| ht,hb,hb|hb|hx|hx | 6 | 3 | |hb|ht|hx |
| hy,hx,hm|hm,hy | 5 | 2 | |hm|hx|hy |
| hz,hy,hx,hm|hm,hy | 6 | 2 | |hm|hx|hy|hz |
+-------------------+-----------------+---------------------+-----------------+

You will have to create a string split table value function (Found one at aspsnippets)
as below
CREATE FUNCTION ufn_SplitString
(
#Input NVARCHAR(MAX),
#Character CHAR(1)
)
RETURNS #Output TABLE (
Item NVARCHAR(1000)
)
AS
BEGIN
DECLARE #StartIndex INT, #EndIndex INT
SET #StartIndex = 1
IF SUBSTRING(#Input, LEN(#Input) - 1, LEN(#Input)) <> #Character
BEGIN
SET #Input = #Input + #Character
END
WHILE CHARINDEX(#Character, #Input) > 0
BEGIN
SET #EndIndex = CHARINDEX(#Character, #Input)
INSERT INTO #Output(Item)
SELECT SUBSTRING(#Input, #StartIndex, #EndIndex - 1)
SET #Input = SUBSTRING(#Input, #EndIndex + 1, LEN(#Input))
END
RETURN
END
GO
Once the Function is in place the below code can be used to achieve the desired result
;WITH cte_OriginalTable(url) as
(
SELECT 'ht,ha,hb,ha|hc|hy' UNION ALL
SELECT 'ht,hb,hb|hb|hx|hx' UNION ALL
SELECT 'hz,hy,hx,hm|hm,hy' UNION ALL
SELECT 'hz,hy,hx,hm|hm,hy'
)
,cte_SaperaterFix AS
(
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS ID, replace(url, ',h', '|h') AS url
FROM cte_OriginalTable
)
,cte_Split as
(
SELECT o.*,
y.Item
FROM cte_SaperaterFix o
CROSS APPLY dbo.ufn_SplitString(o.url, '|') y
)
,cte_TotalCount AS
(
SELECT ID,COUNT(ID) AS counttotal_urls, COUNT(DISTINCT Item) AS Unique_urls, COUNT(ID) - COUNT(DISTINCT Item) AS countduplicate_urls
FROM cte_Split
GROUP BY ID
)
SELECT DISTINCT b.ID, b.url AS URLs, a.CountTotal_URLs, a.CountDuplicate_URLS, STUFF(( SELECT DISTINCT '|' + b1.Item AS [text()]
FROM cte_Split b1
WHERE
b.ID = b1.ID
FOR XML PATH('')
), 1, 1, '' ) AS Unique_URLs, a.Unique_URLs AS CountUnique_URLs
FROM cte_TotalCount a
JOIN cte_Split b
ON a.ID = b.ID

Related

filter out all datetime and integer values from a column in SQL SERVER

I have a string
04/09/2018 06:21:38 101342 CHARLESD JOHNSON:713-269-1878 CALL WHEN WE GET A PO 06/09/2018 08:41:38 101345 KHARLESD KOHNSON:813-269-1878 CALL WHEN WE GET A PO 08/09/2018 09:41:38 10356 THARLESD TOHNSON:913-269-1878 CALL WHEN WE GET A PO
I want output like
DateTime1 | EmpID
04/09/2018 06:21:38 101342
06/09/2018 08:41:38 101345
08/09/2018 09:41:38 10356
Please help
Create the function PatternSplitLoop from this awesome article:
Splitting Strings Based on Patterns
and execute the following:
declare #tab table (string varchar(max))
insert into #tab select '04/09/2018 06:21:38 101342 CHARLESD JOHNSON:713-269-1878 CALL WHEN WE GET A PO 06/09/2018 08:41:38 101345 KHARLESD KOHNSON:813-269-1878 CALL WHEN WE GET A PO 08/09/2018 09:41:38 10356 THARLESD TOHNSON:913-269-1878 CALL WHEN WE GET A PO '
select left(item, 19) DateTime1, substring(item, 20, len(item)) EmpID
from #tab t
cross apply [dbo].[PatternSplitLoop](string, '%[0-9][0-9][/][0-9][0-9][/][0-9][0-9][0-9][0-9]%') f
where matched = 1
Output:
XML split version:
DECLARE #Val NVARCHAR(MAX) = '04/09/2018 06:21:38 101342 CHARLESD JOHNSON:713-269-1878 CALL WHEN WE GET A PO 06/09/2018 08:41:38 101345 KHARLESD KOHNSON:813-269-1878 CALL WHEN WE GET A PO 08/09/2018 09:41:38 10356 THARLESD TOHNSON:913-269-1878 CALL WHEN WE GET A PO '
SELECT #Val = '<a>' + REPLACE(#Val, ' ', '</a><a>') + '</a>';
DECLARE #Xml XML = CONVERT(XML, #Val);
DECLARE #ValTable TABLE
(
ROWNUM INT IDENTITY(1, 1),
Val NVARCHAR(MAX)
)
INSERT into #ValTable
(Val)
SELECT *
FROM
(
SELECT c.value('.', 'NVARCHAR(64)') AS Val
FROM #Xml.nodes('/a') T(c)
) a
WHERE LEN(Val) <> 0
AND (TRY_CONVERT(DATETIME, Val) IS NOT NULL OR TRY_CONVERT(TIME, Val) IS NOT NULL OR TRY_CONVERT(INT, Val) IS NOT NULL);
SELECT CONVERT(DATETIME, CONCAT(a.Val, ' ', b.Val)) AS DateTime1, c.Val AS EmpId
FROM #ValTable a
JOIN #ValTable b
--Date and Time rows, B is time row
ON TRY_CONVERT(TIME, a.Val) IS NOT NULL AND TRY_CONVERT(TIME, b.Val) IS NOT NULL AND b.ROWNUM = a.ROWNUM + 1
-- Int rows
JOIN #ValTable c
ON TRY_CONVERT(INT, c.Val) IS NOT NULL AND c.ROWNUM = a.RowNum + 2;

Could not able to insert the xml data into a table

When i try to insert the values into the table am getting the below error.
We cant remove the space in the XML because it is generated from Javascript.
How to insert the below data into the XMLdata table.
Conversion failed when converting date and/or time from character string.
This is the sample data(#bbhdn5):
341300-02-1|04/10/2018 01:18:29|04/10/2018 06:18:29|133072;
261600-01-1|04/10/2018 06:18:29|04/10/2018 11:18:29|133073;
781100-R1-1|04/10/2018 11:18:29|04/10/2018 16:18:29|133074;
Code:
create table WMC_Savexmldata
(
XML nvarchar(max)
)
Declare #bbhdn5 nvarchar(max)
set #bbhdn5='341300-02-1|04/10/2018 01:18:29|04/10/2018 06:18:29|133072; 261600-01-1|04/10/2018 06:18:29|04/10/2018 11:18:29|133073; 781100-R1-1|04/10/2018 11:18:29|04/10/2018 16:18:29|133074;'
insert into WMC_Savexmldata
select #bbhdn5
Although this question is absolutely misleading, my magic crystal ball started to blink suddenly and told me, that you might be looking for this:
Replacing the delimiters ; and | allows to transfer your CSV-string to this XML:
<x>
<y>341300-02-1</y>
<y>04/10/2018 01:18:29</y>
<y>04/10/2018 06:18:29</y>
<y>133072</y>
</x>
<x>
<y> 261600-01-1</y>
<y>04/10/2018 06:18:29</y>
<y>04/10/2018 11:18:29</y>
<y>133073</y>
</x>
<x>
<y> 781100-R1-1</y>
<y>04/10/2018 11:18:29</y>
<y>04/10/2018 16:18:29</y>
<y>133074</y>
</x>
I use this to get the data as derived table:
DECLARE #bbhdn5 NVARCHAR(MAX);
SET #bbhdn5=N'341300-02-1|04/10/2018 01:18:29|04/10/2018 06:18:29|133072; 261600-01-1|04/10/2018 06:18:29|04/10/2018 11:18:29|133073; 781100-R1-1|04/10/2018 11:18:29|04/10/2018 16:18:29|133074;';
WITH Splitted AS
(
SELECT CAST('<x><y>' + REPLACE(REPLACE(#bbhdn5,'|','</y><y>'),';','</y></x><x><y>') + '</y></x>' AS XML) AS Casted
)
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RowNumber
,A.x.value('y[1]','nvarchar(max)') AS RowCode
,CONVERT(DATETIME,A.x.value('y[2]','nvarchar(max)'),103) AS Date1
,CONVERT(DATETIME,A.x.value('y[3]','nvarchar(max)'),103) AS Date2
,A.x.value('y[4]','int') AS SomeNumber
FROM Splitted
CROSS APPLY Casted.nodes('/x[y/text()]') AS A(x);
The result
+-----------+-------------+-------------------------+-------------------------+------------+
| RowNumber | RowCode | Date1 | Date2 | SomeNumber |
+-----------+-------------+-------------------------+-------------------------+------------+
| 1 | 341300-02-1 | 2018-10-04 01:18:29.000 | 2018-10-04 06:18:29.000 | 133072 |
+-----------+-------------+-------------------------+-------------------------+------------+
| 2 | 261600-01-1 | 2018-10-04 06:18:29.000 | 2018-10-04 11:18:29.000 | 133073 |
+-----------+-------------+-------------------------+-------------------------+------------+
| 3 | 781100-R1-1 | 2018-10-04 11:18:29.000 | 2018-10-04 16:18:29.000 | 133074 |
+-----------+-------------+-------------------------+-------------------------+------------+
UPDATE
Change the line within the CTE Splitted to this
SELECT CAST('<x><y>' + REPLACE(REPLACE(REPLACE(REPLACE(#bbhdn5,CHAR(10),' '),CHAR(13),' '),'|','</y><y>'),';','</y></x><x><y>') + '</y></x>' AS XML) AS Casted
This will replace CHAR(13) and CHAR(10) with blanks. Any odd line break within your input should disappear. Well, you might have some additional blanks in string values. But you can replace doubled blanks with single blanks again...
insert into WMC_Savexmldata
select '496200-01-1|03/31/2018 11:18:29|03/31/2018 16:18:29|133015;245000-01-1|03/31/2018
16:18:29|03/31/2018 21:18:29|133017;262100-13-1|03/31/2018 21:18:29|04/01/2018 02:18:29|133018;'
Please insert the data like this(attached). Date comes in one line and time comes in another line and then run the below query. You will be getting the date time conversion error because of the space error in between date and time. I just want to breaks between the dates. As it is coming from browser the date is coming with space in the SQL. Please help on this. Are you clear with my question.
Declare #InputSepTmp table
(
id int,
Inputs nvarchar(max)
)
insert into #InputSepTmp
Select Row_Number() over (Order By (Select null))
, LTrim(RTrim(B.i.value('(./text())1', 'varchar(max)')))
From (Select x = Cast('' + replace((Select replace(XML,';','§§Split§§') as [*] For XML Path('')),'§§Split§§','')+'' as xml).query('.')
from WMC_Savexmldata) as A
Cross Apply x.nodes('x') AS B(i)
-- select * from #InputSepTmp
--- Cursor --------------------
SET NOCOUNT ON
DECLARE #InputID varchar(200)
DECLARE cur_InputSeparator CURSOR
STATIC FOR
select id from #InputSepTmp where Inputs <> ''
OPEN cur_InputSeparator
IF ##CURSOR_ROWS > 0
BEGIN
FETCH NEXT FROM cur_InputSeparator INTO #InputID
WHILE ##Fetch_status = 0
BEGIN
DEclare #FinalInputtmp table
(
id int,
IPValues varchar(100)
)
insert into #FinalInputtmp
-- SELECT
-- Split.a.value('.', 'NVARCHAR(max)') AS String
--FROM (SELECT
-- CAST ('' + REPLACE(LTRIM(RTRIM(Inputs)), ',', '') + '' AS XML) AS String
-- from #InputSepTmp T1 where id=#InputID) AS A CROSS APPLY String.nodes ('/M') AS Split(a);
Select Row_Number() over (Order By (Select null))
, LTrim(RTrim(B.i.value('(./text())1', 'varchar(max)')))
From (Select x = Cast('' + replace((Select replace(LTRIM(RTRIM(Inputs)),'|','§§Split§§') as [*] For XML Path('')),'§§Split§§','')+'' as xml).query('.')
from #InputSepTmp where id = #InputID) as A
Cross Apply x.nodes('x') AS B(i)
--select convert(datetime,'04/12/2018 12:50:08')
insert into WMC_CriticalPath_ScheduledDtls (SWOPACKAGENO,TASKNO,SCHEDULEDSTDATE,SCHEDULEDENDDATE,TRACKID,CreatedDate,ModifiedDate)
SELECT 'adjb', MAX(CASE WHEN D.RN=1 THEN LTRIM(RTRIM(D.IPValues)) END)[task no]
,MAX(CASE WHEN D.RN=2 THEN LTRIM(RTRIM(D.IPValues)) END) [start date]
,MAX(CASE WHEN D.RN=3 THEN LTRIM(RTRIM(D.IPValues)) END) [end date]
,MAX(CASE WHEN D.RN=4 THEN LTRIM(RTRIM(D.IPValues)) END) [id], Getdate(),NULL
FROM(
SELECT *
,ROW_NUMBER() OVER(ORDER BY (SELECT NULL))RN
FROM #FinalInputtmp
)D
delete from #FinalInputtmp
FETCH NEXT FROM cur_InputSeparator INTO #InputID
END
END
CLOSE cur_InputSeparator
DEALLOCATE cur_InputSeparator
SET NOCOUNT OFF
--select * from WMC_CriticalPath_ScheduledDtls
select * from WMC_CriticalPath_ScheduledDtls

Split a separated value to new single column

I want to separate the | delimited string into new column, I tried the below code but I think is not a good practice.
SELECT
REPLACE(SUBSTRING(ReferenceName, 1, CHARINDEX('|', ReferenceName)), '|', '') AS CreditCard,
ReferenceName
FROM
CTS.DBO.cts_TxSalesPayment
Expected result
Split the value based on the delimiter:
CardNumber | ExpiryDate | ApprovalCode | .... | ... | ... | ...
One way would be to use a REPLACE function to allow the column to be parsed as XML, then PIVOT the result.
For example:
DECLARE #T TABLE (ReferenceName VARCHAR(MAX));
INSERT #T VALUES ('CardNumber=asdf|ExpiryDate=1234124x|ApprovalCode=aaaaa'), ('CardNumber=zzz|ExpiryDate=123|ApprovalCode=q'), ('CardNumber=zzz|ExpiryDate=111|ApprovalCode=q2');
SELECT *
FROM
(
SELECT RN, colName = A.B.value('local-name(.)', 'varchar(max)'), colVal = A.B.value('#val', 'varchar(max)')
FROM
(
SELECT RN = ROW_NUMBER() OVER (ORDER BY (SELECT NULL)), col = CAST('<' + REPLACE(REPLACE(ReferenceName, '=', ' val='''), '|', '''/><') + ''' />' AS XML)
FROM #T
) AS T
CROSS APPLY col.nodes('*') AS A(B)
) AS T
PIVOT
(
MAX(colVal) FOR colName IN ([CardNumber], [ExpiryDate], [ApprovalCode])
) AS P;

need help in forming sql query

ItemId Name parentId
1 A null
2 b null
3 c 1
4 d 2
5 e 3
6 f 4
7 g 2
hi i need help in create sql query. I have a table that contain 3 column itemid ,name ,parentitemid. i need a sql query that result parent child relation.if parentitemid id null then it means root .please help
i need data like.
<1><3><5></5> </3></1>
For example you can use:
WITH HierarchicalTable
AS
(
SELECT Id, ParentId, Name, 0 as [Level]
FROM YourTable
WHERE ParentId IS NULL
UNION ALL
SELECT YourTable.Id, YourTable.ParentId, YourTable.Name, [Level] + 1
FROM YourTable
JOIN HierarchicalTable ON HierarchicalTable.Id = YourTable.ParentId
)
SELECT [Level], Name FROM HierarchicalTable
This is excessively complicated solution, but it will work for your problem:
DECLARE #temp TABLE (ItemId int, Name char(1), parentId int,l int)
DECLARE #xml TABLE (s nvarchar(max), e nvarchar(max), parentId int, itemid int)
DECLARE #l int
;WITH cte AS (
SELECT *
FROM (VALUES
(1, 'a', NULL),(2, 'b', NULL),(3, 'c', 1),(4, 'd', 2),(5, 'e', 3),(6, 'f', 4),(7, 'g', 2)
) as t(ItemId, Name, parentId)
--Here we create recursive cte to obtain levels of nesting
), res AS (
SELECT *,
1 [Level]
FROM cte c
where parentId IS null
UNION ALL
SELECT c.*,
[Level]+1
FROM res r
INNER JOIN cte c
ON c.parentId = r.ItemId
)
--put results into temp table
INSERT INTO #temp
SELECT *
FROM res
--obtain max level
SELECT #l = MAX(l)
FROM #temp
--from max level to 1 begin
WHILE #l > 0
BEGIN
--if there is nodes with same parentid - concatinating them
UPDATE x
SET x.e = x.e + v.s + v.e
FROM #xml x
INNER JOIN #xml v
ON v.parentId = x.parentId and v.e !=x.e;
--here we merge table with results
-- first run <e></e>
-- next run <c><e></e></c>
-- next run <a><c><e></e></c></a>
MERGE #xml AS target
USING (
SELECT '<'+ Name +'>' as s,'</'+ Name + '>' as e, parentId, ItemId
FROM #temp
WHERE l = #l
) as source
ON target.parentid = source.itemid
WHEN NOT MATCHED THEN INSERT VALUES (source.s, source.e, source.parentId, source.ItemId)
WHEN MATCHED THEN
UPDATE
SET target.s = source.s + target.s,
target.e = target.e + source.e,
target.parentid = source.parentid,
target.itemid = source.itemid;
--next level down
SET #l = #l - 1
END
SELECT x --CAST(x as xml)
FROM (
SELECT s+e as x,
DENSE_RANK() OVER (PARTITION BY itemid ORDER BY s ASC) as rn
--need that column to obtain first one of every string for itemid
FROM #xml
) as c
WHERE c.rn = 1
--FOR XML PATH ('')
Output will be:
x
<a><c><e></e></c></a>
<b><d><f></f></d><g></g></b>
If you remove -- near FOR XML PATH ('') and change this SELECT x --CAST(x as xml) to this SELECT CAST(x as xml) in last query you will get this:
<a>
<c>
<e />
</c>
</a>
<b>
<d>
<f />
</d>
<g />
</b>

How to sum data from string

Have table :
id name
1 A1=7|A5=1|A10=5|A20=12|A50=8
2 A1=10|A5=2|A10=10|A20=14|A50=4
3 A1=3|A5=3|A10=5|A20=12|A50=8
.
.
Want sum all A1,A5,A10,A20,A50
Response must be like :
A1=20|A5=6|A10=20|A20=38|A50=20
How to do it ?
I also upvoted comment about changing table design but there are situations when somebody cannot do this. So here is the solution for this case and it's not so difficult. We call XML for assistance as usual when need to process formatted strings in XML columns.
-- Prepare data for solution testing
DECLARE #srctable TABLE (
id INT,
name VARCHAR(999),
namexml XML
)
INSERT INTO #srctable
SELECT id, name, namexml FROM ( VALUES
(1, 'A1=7|A5=1|A10=5|A20=12|A50=8', null),
(2, 'A1=10|A5=2|A10=10|A20=14|A50=4', null),
(3, 'A1=3|A5=3|A10=5|A20=12|A50=8', null)
) v (id, name, namexml)
-- Transform source formatted string to XML string
UPDATE #srctable
SET namexml = CAST('<row><data ' + REPLACE(REPLACE(name, '|', '"/><data '), '=', '="') + '"/></row>' AS XML)
-- Final select from XML data
SELECT SUM(x.data.value('(#A1)[1]', 'INT')) AS SUMA1,
SUM(x.data.value('(#A5)[1]', 'INT')) AS SUMA5,
SUM(x.data.value('(#A10)[1]', 'INT')) AS SUMA10,
SUM(x.data.value('(#A20)[1]', 'INT')) AS SUMA20,
SUM(x.data.value('(#A50)[1]', 'INT')) AS SUMA50
FROM #srctable AS t
CROSS APPLY t.namexml.nodes('/row/data') x (data)
You need to format your resulting string in any way you wish.
Variant without xml:
--------------------------------------------------------------------------------
-- Prepare data for solution testing
DECLARE #srctable TABLE ( id INT
, NAME VARCHAR(999) )
INSERT INTO #srctable
VALUES ( 1, 'A1=7|A5=1|A10=5|A20=12|A50=8' )
, ( 2, 'A1=10|A5=2|A10=10|A20=14|A50=4' )
, ( 3, 'A1=3|A5=3|A10=5|A20=12|A50=8' )
--------------------------------------------------------------------------------
-- prepare temp table for using in split string
DECLARE #Tally TABLE ( N INT )
DECLARE #i AS INT = 1
WHILE #i != 1000
BEGIN
INSERT INTO #Tally ( N )
VALUES ( #i )
SET #i = #i + 1
END
--------------------------------------------------------------------------------
--final query
;WITH cte AS
(
SELECT id,
(CASE WHEN CHARINDEX('|', S.string) > 0
THEN left(S.string, CHARINDEX('|', S.string) - 1)
ELSE string END ) NAME
FROM #srctable AS E
INNER JOIN #Tally AS T ON SUBSTRING('|' + NAME, T.N, 1) = '|'
AND T.N <= LEN(NAME)
CROSS APPLY (SELECT String = (CASE WHEN T.N = 1
THEN LEFT(E.NAME, CHARINDEX('|', E.NAME) - 1)
ELSE SUBSTRING(E.NAME, T.N, 1000) END )
) AS S
)
SELECT LEFT(NAME, CHARINDEX('=', NAME) - 1) AS NAME,
SUM(convert(float,RIGHT(NAME, CHARINDEX('=', REVERSE(NAME)) - 1))) AS Value
FROM cte
GROUP BY LEFT(NAME, CHARINDEX('=', NAME) - 1)

Resources