Reputation: 81379
I have an SQLite database that stores a list of items with categories. Categories are implicit, there is no separate table for them. I would like a single query that would return all items ordered by category, with an extra row per category.
Consider the following scenario:
ID Name Category
1 Item 1 C1
2 Item 2 C2
3 Item 3 C1
The results I expect would be something like:
ID Name Category
null null C1
1 Item 1 C1
3 Item 3 C1
null null C2
2 Item 2 C2
This is to have a direct mapping to the list view where the results will be displayed, that contain an extra separator item per category. What I'm doing right now is return all elements ordered by category, and iterate over all of them to know where the separators should be located.
I have experimented with a number of different JOIN
s, but my SQL-fu is weak and I cannot figure out how to write such query. How would I go about doing this? Which SQL constructs would let me add those extra rows? Is it even possible to get the results in the way I need them in a single -no matter how complex- query?
Upvotes: 0
Views: 61
Reputation: 238176
Consider a union
:
select ID
, Name
, Category
union all
select distinct null
, null
, Category
order by
Category
An order by
applies to the entire union-- no need for a subquery.
Upvotes: 1