SQL - 添加来自不同 ID 的同一列的值

SQL - Adding values from same column of different IDs

我有 2 个表格产品和库存,如下所示。

Product:

Product_ID     Product_Description    Price
100            Computer               30
200            Laptop                 50
300            Printer                10

Inventory:

Product_ID   Stock
100          40
200          15
300          50

从这两个表中,我需要查询以列出具有最大库存数量的产品 ID、产品描述和数量,并将笔记本电脑的库存添加到显示中。

Expected Output:

Product_ID   Product_Description   Stock
300          Printer               65

65 是打印机 50 和笔记本电脑 15 的结果。

能否请您尽快帮忙查询一下?

您可以使用 window 功能。这使用一个技巧将数据减少到两行,使用 window 函数将库存加起来,然后只为非笔记本电脑行(如果有的话)选择一行。

select p.*, sum(stock) over ()
from (select s.*, row_number() over (order by stock desc) as seqnum
      from stock s
     ) s join
     product p
     on p.product_id = s.product_id
where s.seqnum = 1 or p.product_description = 'Laptop'
order by s.seqnum
limit 1;

您可以使用 MAX() 聚合函数来完成:

SELECT p.Product_ID, p.Product_Description, 
       MAX(CASE WHEN p.Product_Description = 'Laptop' THEN i.Stock END) + 
       MAX(i.Stock) Stock
FROM Product p INNER JOIN Inventory i
ON i.Product_ID = p.Product_ID 

此代码依赖于 SQLite 的功能 return 包含最大值的行(在本例中为最后定义的最大值)。

参见demo
结果:

Product_ID Product_Description Stock
300 Printer 65