问题
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