【问题标题】:Find customer ids who ordered more in 2019 than they did in 2018查找 2019 年比 2018 年订购更多的客户 ID
【发布时间】:2021-09-07 16:34:43
【问题描述】:

这是在一次采访中被问到的。

下面是表格的结构。

Shipments- Shipment_id,Price, Order_id, Ship_date, Delivery_Location, Price, Ship_method , ShipETA,
Customer-Customer_id, order_id, customer_address, prime_eligible
Order - Order_id , Order_Qty, Order_date , Order_location, Item_id , Shipment_id
Item- Item _id , Item_description, Item_Location

问题:2019 年订购量比 2018 年多的客户 ID 列表。

    SELECT customer_id
FROM Customer join Order using (order_id)
WHERE YEAR(Order_date) IN (2019)
GROUP BY customer_id
HAVING
    SUM(CASE WHEN YEAR(Order_date) = 2019 THEN Order_Qty ELSE 0 END)
    >  SUM(CASE WHEN YEAR(Order_date) = 2018 THEN Order_Qty ELSE 0 END)

很遗憾,我没有样本数据,任何人都可以帮助解决这个问题。

【问题讨论】:

  • GROUP BY、HAVING、sum case 等
  • 是的,我只是坚持如何逐年比较并列出用户的方法,因为我是 SQL 新手,任何示例查询都会有很大帮助。
  • 这里需要一些努力。轻松协助您,编造一些数据并找出预期的结果。 minimal reproducible example
  • 另外,不同的产品有不同的 SQL 功能集——你想知道哪一个?
  • 当然我会设置示例数据并很快发布到这里。这是针对 Oracle 数据库问题的。

标签: sql oracle


【解决方案1】:

您发布的数据模型看起来有些“奇怪”;我不会将ORDER_ID 保留在CUSTOMER 表中,它只是不属于那里。我会将CUSTOMER_ID 添加到SHIPMENT 中。

无论如何,这是一个选择:

  • 第 1 - 21 行中的样本数据
  • temp CTE 计算每个客户和年份(仅 2018 年和 2019 年)的汇总(订购数量)
  • 最终查询仅检查 2019 年比 2018 年订购更多商品的人

SQL> with
  2  customer (customer_id, order_id) as
  3    (select 'A', 1 from dual union all
  4     select 'A', 3 from dual union all
  5     select 'B', 2 from dual union all
  6     select 'B', 4 from dual union all
  7     select 'B', 5 from dual union all
  8     --
  9     select 'A', 6 from dual
 10    ),
 11  orders (order_id, order_qty, order_date) as
 12    -- A's summaries: 2018: 100 / 2019: 400
 13    -- B's summaries: 2018: 400 / 2019: 300  --> should be returned
 14    (select 1, 100, date '2018-05-03' from dual union all -- A
 15     select 2, 200, date '2018-07-23' from dual union all -- B
 16     select 3, 400, date '2019-04-02' from dual union all -- A
 17     select 4, 300, date '2019-08-14' from dual union all -- B
 18     select 5, 200, date '2018-11-14' from dual union all -- B
 19     --
 20     select 6, 900, date '2020-01-01' from dual           -- A
 21    ),
 22  -- summaires per customers and years

 23  temp as
 24    (select c.customer_id,
 25       extract(year from o.order_date) as year,
 26       sum(o.order_qty) sum_qty
 27     from customer c join orders o on o.order_id = c.order_id
 28     where extract(year from o.order_date) in (2018, 2019)
 29     group by c.customer_id,
 30              extract(year from o.order_date)
 31    )
 32  select t.customer_id
 33  from temp t
 34  group by t.customer_id
 35  having sum(case when t.year = 2019 then t.sum_qty end) <
 36         sum(case when t.year = 2018 then t.sum_qty end);

CUSTOMER_ID
-----------
B

SQL>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-28
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    相关资源
    最近更新 更多