子查询值大于另一个子查询值

时间:2017-09-11 14:11:03

标签: sql oracle subquery

我有一个返回8列的查询,其中2列是返回最大日期的子查询。我想创建第9列,它将返回一个数字,星号或其他内容,以突出显示第1列中的日期大于第2列但仍保留所有行的行。有可能吗?

编辑: 这是查询 我希望看到差异的列是MaxExpDateGB和MaxExpDatePH

select
i.ITEM,
i.COMPANY,
count(distinct i.LOGISTICS_UNIT) as LocationsGB,
sum(on_hand_qty) as StockGB,
(select
Count(distinct location)
from
LOCATION_INVENTORY b where b.ITEM = i.ITEM and b.TEMPLATE_FIELD1 = '139' and b.TEMPLATE_FIELD4 is not null and b.TEMPLATE_FIELD5 is null) as LocationsPH,
(select
sum(on_hand_qty)
from
LOCATION_INVENTORY b where b.ITEM = i.ITEM and b.TEMPLATE_FIELD1 = '139' and b.TEMPLATE_FIELD4 is not null and b.TEMPLATE_FIELD5 is null) as StockPH,
MAX(i.Expiration_DATE) as MaxExpDateGB,
(select
MAX(a.Expiration_DATE)
from
LOCATION_INVENTORY a where a.ITEM = i.ITEM and a.TEMPLATE_FIELD1 = '139' and a.TEMPLATE_FIELD4 is not null and a.INVENTORY_STS = 'available' ) as MaxExpDatePH
from
LOCATION l inner join LOCATION_INVENTORY i on l.LOCATION = i.LOCATION inner join ITEM t on i.ITEM = t.ITEM
where
t.USER_DEF6 = '10'
and i.LOCATION = '000-gb-01'
group by
i.item,i.company

1 个答案:

答案 0 :(得分:1)

没有任何重构

select *, case when LocationsPH > StockPH then '*' end flag
from (
    select
        i.ITEM,
        i.COMPANY,
        count(distinct i.LOGISTICS_UNIT) as LocationsGB,
        sum(on_hand_qty) as StockGB,
        (select
            Count(distinct location)
            from
            LOCATION_INVENTORY b where b.ITEM = i.ITEM and b.TEMPLATE_FIELD1 = '139' and b.TEMPLATE_FIELD4 is not null and b.TEMPLATE_FIELD5 is null
        ) as LocationsPH,
        (select
            sum(on_hand_qty)
            from
            LOCATION_INVENTORY b where b.ITEM = i.ITEM and b.TEMPLATE_FIELD1 = '139' and b.TEMPLATE_FIELD4 is not null and b.TEMPLATE_FIELD5 is null
        ) as StockPH,
        MAX(i.Expiration_DATE) as MaxExpDateGB,
        (select
            MAX(a.Expiration_DATE)
            from
            LOCATION_INVENTORY a where a.ITEM = i.ITEM and a.TEMPLATE_FIELD1 = '139' and a.TEMPLATE_FIELD4 is not null and a.INVENTORY_STS = 'available' 
        ) as MaxExpDatePH
    from
    LOCATION l 
    inner join LOCATION_INVENTORY i on l.LOCATION = i.LOCATION inner join ITEM t on i.ITEM = t.ITEM
    where
    t.USER_DEF6 = '10'
    and i.LOCATION = '000-gb-01'
    group by
    i.item,i.company
) t