我在MS Access中有表(Product_Id,category priority,atribute1,atribute2 ...),我正在尝试进行查询,按类别对数据进行排序并按最高优先级排序。优先级可以为空,因此应该放在最后。 例: 表
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
查询中预期的结果:
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
答案 0 :(得分:3)
在Jet SQL中,这可能适合:
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);
答案 1 :(得分:1)
最简单的解决方案(在某些情况下不一定是最好的)是在订购表达式中使用列号:
SELECT t2.MinOfPriority,
tn.Field2,
Nz([tn.Field3],999) AS Priority,
tn.Field4,
tn.Field5
ORDER BY 1,2,3
答案 2 :(得分:0)
你需要对类别进行加权(我用一些适当大的值加权null):
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)
答案 3 :(得分:-1)
据我所知,当使用显式ORDER BY时,Jet 总是将NULL分类到结果集的末尾。
请参阅:ADO Provider Properties and Settings
“NULL归类顺序:一个Long值(只读),指定Null值的整理(排序)。对于Microsoft Jet提供程序,值始终为4,表示空值在低端排序列表。“
属性NULL Collation Order对提供程序是只读的这一事实强烈建议Jet引擎只有一个NULL排序规则,并且很高兴为您提供所需的。
答案 4 :(得分:-1)
Apparently NZ(Value,ValueToReturnIfNull)可以在MS Access上用作ISNULL的替代品,所以......
SELECT a.*
FROM this_table AS a
INNER JOIN
(
SELECT category,min(NZ(priority,999999)) as min_priority_in_cat
FROM this_table group by category
) AS b ON a.category = b.category
ORDER BY b.min_priority_in_cat, a.category, NZ(a.priority,999999)