How to order an SQL query with grouped rows
I have a table (Product_Id, category priority, atribute1, atribute2 ...) in MS Access and I am trying to make a query that orders the data, grouped by categories and ordered by highest priority. The priority can be zero, so it should be placed at the end. Example: Table
1, 100, 2, atr1, atr2 2, 300, , atr1, atr2 3, 100, 5, atr1, atr2 4, 200, 9, atr1, atr2 5, 100, , atr1, atr2 6, 200, 1, atr1, atr2
Expected result in request:
6, 200, 1, atr1, atr2 4, 200, 9, atr1, atr2 1, 100, 2, atr1, atr2 3, 100, 5, atr1, atr2 5, 100, , atr1, atr2 2, 300, , atr1, atr2
In Jet SQL, this might work:
SELECT t2.MinOfPriority, tn.Field2, Nz([tn.Field3],999) AS Priority,
tn.Field4, tn.Field5
FROM tn
INNER JOIN (SELECT Min(Nz(tn.Field3,999)) AS MinOfPriority, tn.Field2
FROM tn GROUP BY tn.Field2) AS t2 ON tn.Field2 = t2.Field2
ORDER BY t2.MinOfPriority, tn.Field2, Nz([Field3],999);
source to share
You need to weight the categories (I weight zero with some suitable large value):
select t1.*
from myTable t1
join
(
select category, min(coalesce(priority, 1000)) weight
from myTable
group by category
) t2
on t1. category = t2. category
order by t2.weight, coalesce(t1. priority, 1000)
source to share
As far as I know, Jet always sorts NULL at the end of the result set when an explicit ORDER BY is used.
See: ADO Provider Properties and Settings
"NULL Order Collation: Long (read-only) value that indicates where the Null values are collated (sorted). For the Microsoft Jet provider, the value is always 4, which indicates that null values are sorted at the bottom of the list."
The fact that the NULL Collation Order property is read-only, the vendor strongly suggests that the Jet engine has only one set of NULL values, and luckily for you, this is the one you want.
source to share