Group data on different key-value pairs in a string

心已入冬 提交于 2020-04-18 06:11:33

问题


I have a table LOG that contains a field NOTES. Table LOG also contains a field NrofItems. This is on Azure SQL. NOTES is a string that contains key-value pairs separated by semicolons. The order of the key-value pairs is random. The keys are known.

Example of three records:

NOTES | NrofItems    
"customer=customer1;code=blablabla;application=SomeApplication"  | 23
"code=adfadfadf;customer=customer99;application=AlsoApplication" | 33
"code=xyzxyzxyz;application=AlsoApplication;customer=customer1"  | 13
"code=blablabla;customer=customer1;application=SomeApplication"  |  2

I need to sum the value of NrofItems per customer per application per... like this:

customer1  | blablabla | SomeApplication | 25
customer1  | xyzxyzxyz | AlsoApplication | 13
customer99 | adfadfadf | AlsoApplication | 33

I would like to be able to use one or more of the key-value pairs to make groupings.

I do know how to to it for one grouping but how for more?

See this URL to see how to do it for one grouping: Group By on part of string


回答1:


Hmmm. For this, I'm thinking that extracting the customer and application separately is a convenient way to go:

select c.customer, a.application, sum(nrofitems)
from t outer  apply
     (select top (1) stuff(s.value, 1, 10, '') as customer
      from string_split(t.notes, ';') s
      where s.value like 'customer=%'
     ) c outer apply
     (select top (1) stuff(s.value, 1, 12, '') as application
      from string_split(t.notes, ';') s
      where s.value like 'application=%'
     ) a
group by c.customer, a.application;

Here is a db<>fiddle.



来源:https://stackoverflow.com/questions/61259157/group-data-on-different-key-value-pairs-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!