【问题标题】:how to add a conditional statement after calculating two fields in SQLSQL中计算两个字段后如何添加条件语句
【发布时间】:2019-08-29 12:34:48
【问题描述】:

我需要根据条件输出数据以将输出限制为可用数据。在理解和优化查询以及删除我的 SQL 查询的冗余方面需要帮助

我在 where 语句中尝试了条件,但这给了我一个错误。还尝试添加一个 Have 语句,它也不起作用。

select
  o2.car_move_id as Carrier_Code,
  o1.early_shpdte,
  o1.prtnum,
  shpsts,
  (o1.host_ordqty / o3.untqty) as Order_pallets,
  (
    select
      count(i3.untqty)
    from
      INVENTORY_PCKWRK_VIEW i3
      inner join prtftp_dtl i4 on i3.prtnum = i4.prtnum
    where
      i3.invsts like 'U'
      and i3.wrkref is null
      and i3.prtnum = o1.prtnum
      and i3.untqty = i4.untqty
      and i4.uomcod like 'PL'
      and i4.wh_id like 'RX'
  ) as full_pallets,
  (
    select
      count(i5.untqty)
    from
      INVENTORY_PCKWRK_VIEW i5
      inner join prtftp_dtl i6 on i5.prtnum = i6.prtnum
    where
      i5.invsts like 'U'
      and i5.wrkref is null
      and i5.prtnum = o1.prtnum
      and i5.untqty < i6.untqty
      and i5.prtnum = i6.prtnum
      and i6.uomcod like 'PL'
      and i6.wh_id like 'RX'
  ) as Partial_pallets
from
  ord_line o1
  inner join SHIP_STRUCT_VIEW o2 on o1.ordnum = o2.ship_id
  inner join prtftp_dtl o3 on o1.prtnum = o3.prtnum
where
  o2.ship_id like '0%'
  and shpsts in ('R', 'I')
  and o1.non_alc_flg = 0
  and o3.wh_id like 'RX'
  and o3.uomcod like 'PL'
order by
  full_pallets asc,
  o1.early_shpdte asc

我只想输出 order_pallets > Full_Pallets 的查询。不确定我可以在查询中的何处添加此条件。

【问题讨论】:

  • 您是否使用代码格式化标签发布过。
  • WHERE 条款HAVING 条款,而不是字段。

标签: sql


【解决方案1】:

SQL 查询的SELECT 列表中的项目在WHERE 子句(如this answer 中所述)之后进行逻辑处理,这就是为什么您不能在@ 中引用列别名的原因987654324@ 子句。您将需要使用子选择来完成您想要的:

select * from (
  select
    o2.car_move_id as Carrier_Code,
    o1.early_shpdte,
    o1.prtnum,
    shpsts,
    -- the rest of your current query
) t
where t.order_pallets > t.Full_Pallets

【讨论】:

  • 这真的很有帮助。谢谢
  • @AmmarBhotwawala 如果解决了您的问题,请接受答案!
【解决方案2】:

您可以将整个查询包含在

with x as ()

然后从中选择:

select * from x 
where x.order_pallets > x.full_pallets

这将使您不必为相同的信息维护多个子查询。

【讨论】:

    猜你喜欢
    • 2023-03-04
    • 2011-02-18
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2016-01-02
    相关资源
    最近更新 更多