简体   繁体   中英

SQL sort based on comma-separated string?

Say that I have a table that looks like this (sorry about using a picture, but I can't figure out how to get a nicely-formatted table on SO...):

食谱和成分

I wanted to make a query to sort the ingredients by the frequency of recipes they appear in. So in this example, we'd want to see the following output:

成分排序

I was thinking that LIKE and IN might be potentially helpful to make this search, but I'm not sure how to go from there.

I really can't resist a "you can't" quote. Your solution follows.

SELECT Item
FROM
(
    SELECT LTRIM(x.XmlCol.value('.','varchar(100)')) 'Item'
    FROM 
    (
        SELECT CAST('<A>'+REPLACE(ingredients,',','</A><A>')+'</A>' AS XML) 'Ingredient'
        FROM #recipes ) Mytab
    CROSS APPLY Mytab.Ingredient.nodes('/A') x(xmlcol)
) Listing
GROUP BY ITEM
ORDER BY Count(1) DESC

Try it for yourself. In short you start by replacing the commas with XML seperators, Then for efficiency invoke Microsofts own XML methods to convert the list of values into a tabular output. You then simply drop the lot into a FROM statement and group with an order by.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM