【问题标题】:can we use Join, Case and where clause together我们可以同时使用 Join、Case 和 where 子句吗
【发布时间】:2021-03-09 09:50:53
【问题描述】:

编写查询以显示(product_class_desc, product_id, product_desc, product_quantity_avail ),并根据可用数量显示产品的库存状态如下:

一个。对于电子和计算机类别,

  • 如果可用数量
  • 如果 11
  • 如果 >= 31,则显示“库存充足”

b.对于文具和服装类别,

  • 如果数量
  • 如果 21
  • 如果 >= 81,则显示“库存充足”

c。其余类别,

  • 如果数量
  • 如果 16
  • 如果 >= 51 – '库存充足'

对于所有类别,如果可用数量为 0,则显示“缺货”。

product_class_desc, product_id, product_desc 来自product

product_quantity_avail 来自product_overview 表。

case 和 where 子句可以一起使用吗? product_quantity_avail 来自另一个表,因此也必须进行内部连接。

有人可以帮助我如何检索这些数据吗?

【问题讨论】:

  • 在 ON 和 WHERE 子句中使用 AND/OR 结构而不是 case 表达式通常会更好。
  • mysql和sqlite是两种不同的数据库产品,sql的实现方式不同。删除了冲突的产品标签。请添加您实际使用的那个。
  • 问题不清楚,请通过添加示例数据和预期输出来澄清。
  • 用您正在使用的数据库标记您的问题。

标签: sql


【解决方案1】:

您可以使用 case 语句并连接 product 和 product_overview 表来实现此目的。

select p.product_class_desc, p.product_id, p.product_desc, 
case when pw.product_quantity_avail = 0 then 'Out of stock' 
     when p.product_class_desc in ('Electronics','Computer') then
          case when pw.product_quantity_avail <= 10 then 'Low stock'
               when pw.product_quantity_avail between 11 and 30 then 'In stock'
               when pw.product_quantity_avail >= 31 'Enough stock' 
          end
     when p.product_class_desc in ('Stationery','Clothes') then
          case when pw.product_quantity_avail <= 20 then 'Low stock'
               when pw.product_quantity_avail between 21 and 80 then 'In stock'
               when pw.product_quantity_avail >= 81 'Enough stock' 
          end
     when pw.product_quantity_avail <= 15 then 'Low stock'
     when pw.product_quantity_avail between 16 and 50 then 'In stock'
     when pw.product_quantity_avail >= 51 'Enough stock' 
     end
from product p
inner join product_overview pw on p.product_id = pw.product_id

【讨论】:

    【解决方案2】:

    是的,您可以同时使用 where、case 和 join。 如果您使用的是 case 条件,那么如果这就是意图,则必须在 where 语句中重写它。 我猜你说的是 MS-SQL。

    例如 选择product_class_desc、product_id、product_desc、 数量

    来自 table_xx 内连接 table_yy on product_id = productid

    【讨论】:

      猜你喜欢
      • 2017-05-07
      • 2012-03-07
      • 2012-05-02
      • 2023-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-27
      相关资源
      最近更新 更多