简体   繁体   中英

SQL query to return category if sub_items exist AND 'other name' if sub_items exist outwith category

Apologies if the title is confusing. Essentially, we have a set of hierarchy tables of categories, groupings, collections etc with individual items at the bottom of the hierarchy.

So on the whole, we have something like Category > Grouping > Collection > Item. However, some items are not part of a collection. What I need is a query which will return the Collection details if at least one Item exists within the Collection for given search terms, and 'Other' (a flag value or something) if items exist within the Category and Grouping, but are not in a Collection (foreign key 'collection_id' will be null in this case).

The outcome I'm trying to achieve is something like:

Collection Name 1
    Item
    Item
    ...
Collection Name 2
    Item
    Item
    ...
Collection Name X
    Item
    ...
Other Items
    Item
    Item
    ...

Is it possible (and simple enough) to do this with one query?

This isn't going to format the data just like you indicated, but it seems like something along the lines of SELECT CASE WHEN CollectionID IS NULL THEN 'Other Items' ELSE CollectionName END, ItemName would do the trick. I'm a SQL Server guy mostly, but I think that's pretty standard SQL.

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