按条件排序

时间:2017-08-18 11:40:10

标签: sql oracle

我有两个表,ProductsCategory。每个product与特定Category相关,并且Expiry_Date可能为NULL值。

我想首先查询最快products订购的所有Expiry_Date。 Null-Expiry_date产品最后为具有特定名称的Category订购,例如Food

更新(以下样本数据):

产品表:

enter image description here

类别表:

enter image description here

结果:

enter image description here

2 个答案:

答案 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