代码之家  ›  专栏  ›  技术社区  ›  Daniil Shipilov

有人能帮我写下面的sql脚本吗

  •  0
  • Daniil Shipilov  · 技术社区  · 3 年前

    我希望这个脚本不会输出0值,但它会。我想这是因为 and (select sum(lot_movement.quantity) FROM lot_movement where lot_movement.lot_id = lot.id) > 0 0值将不会输出。我做错了什么?

    select lot.*, sum(movement.quantity) as value 
    from lot
    left join lot_movement as movement on lot.id = movement.lot_id
    where lot.item_id = 8 and movement.storage_id = 3 and 
    (select sum(lot_movement.quantity) 
      FROM lot_movement 
      where lot_movement.lot_id = lot.id) > 0
    group by lot.id;
    

    我试着加上“和”(lot_movement.quantity)>0”,但这会导致“组函数的无效使用”问题

    lots in database

    lot_movements in database

    output with 0 values

    我看到了“和”(从lot_movement中选择sum(lot_movement.quantity),其中lot_movement。lot_id=lot。身份证分组抽签运动。地段(id)>0'是redundent。这对结果没有影响。那么,我怎样才能获得0值的输出呢?

    1 回复  |  直到 3 年前
        1
  •  0
  •   Marleen    3 年前

    您的查询没有给出预期的结果,因为您正在按 lot.item_id = 8 and movement.storage_id = 3 where 子句,但在子选择中没有应用相同的筛选。

    我不太确定你想达到什么目的,但我怀疑增加了 having 子句而不是subselect解决了您的问题:

    select lot.id, sum(movement.quantity) as value 
    from lot
    left join lot_movement as movement on lot.id = movement.lot_id
    where lot.item_id = 8 and movement.storage_id = 3
    group by lot.id
    having sum(movement.quantity) > 0