我有两个表,Products
和Category
。每个product
与特定Category
相关,并且Expiry_Date
可能为NULL
值。
我想首先查询最快products
订购的所有Expiry_Date
。 Null-Expiry_date产品最后为具有特定名称的Category
订购,例如Food
。
产品表:
类别表:
结果:
答案 0 :(得分:1)
这不仅仅是关于排序,你想要排除一些具有空日期的行,但是包括基于类别名称的其他行;然后订购剩下的东西:
select p.prod_id, p.name, p.expiry_date, c.cat_id
from product p
join category c on c.cat_id = p.cat_id
where (c.name = 'Food' or p.expiry_date is not null)
order by p.expiry_date desc nulls last;
where
子句排除产品将为空过期日期,除非它们属于“食品”类别。顺序是直截了当的,虽然你想要按降序日期顺序,你需要specify nulls last
来获取那些......呃......最后。
使用CTE中的样本数据进行演示:
with product (prod_id, name, expiry_date, cat_id) as (
select 1, 'NAME1', date '2018-01-10', 1 from dual
union all select 2, 'NAME2', date '2018-01-11', 2 from dual
union all select 3, 'NAME3', date '2018-01-12', 3 from dual
union all select 4, 'NAME4', null, 1 from dual
union all select 5, 'NAME5', null, 2 from dual
union all select 6, 'NAME6', date '2018-01-13', 2 from dual
union all select 7, 'NAME7', date '2018-01-14', 2 from dual
union all select 8, 'NAME8', null, 3 from dual
),
category (cat_id, name) as (
select 1, 'Food' from dual
union all select 2, 'Food1' from dual
union all select 3, 'Food2' from dual
)
select p.prod_id, p.name, p.expiry_date, c.cat_id
from product p
join category c on c.cat_id = p.cat_id
where (c.name = 'Food' or p.expiry_date is not null)
order by p.expiry_date desc nulls last;
PROD_ID NAME EXPIRY_DAT CAT_ID
---------- ----- ---------- ----------
7 NAME7 2018-01-14 2
6 NAME6 2018-01-13 2
3 NAME3 2018-01-12 3
2 NAME2 2018-01-11 2
1 NAME1 2018-01-10 1
4 NAME4 1
答案 1 :(得分:0)
如果我理解正确,只需在nulls last
中使用order by
:
select c.category, p.*
from products p join
category c
on p.? = c.? -- whatever the join keys are
order by category, expiry_date nulls last