sqlite 如何在单独的列和行中拆分数量

g6ll5ycj  于 2023-01-21  发布在  SQLite
关注(0)|答案(1)|浏览(160)
    • 详细信息**

以下是我的表和数据:

create table orders (
  id int not null,
  item varchar(10),
  quantity int
 );
 
 insert into orders (id, item, quantity) values
 (1, 'Item 1', 10);
 
 create table orders_picked (
  id int not null,
  orderId int,
  quantity int
 );
 
  insert into orders_picked (id, orderId, quantity) values
 (1, 1, 4),
 (2, 1, 1);

为了获得已挑选项目的计数,我运行以下查询:
select item, sum(op.quantity) as quantity from orders o left join orders_picked op on o.id = op.orderId group by item
这是输出:

    • 问题**

因为表orders有5个剩余物料需要拣货,如何将剩余物料分行显示,并额外增加一列标识是"拣货"还是"剩余"?如下所示:

ymdaylpp

ymdaylpp1#

使用CTE连接表并进行聚合,然后使用UNION ALL为 * picked * 和 * remaining * 获取单独的行:

WITH cte AS (
  SELECT o.item,
         o.quantity,
         TOTAL(op.quantity) AS picked_quantity  
  FROM orders o LEFT JOIN orders_picked op 
  ON op.orderId = o.id 
)  
SELECT item, picked_quantity AS quantity, 'Picked' AS Type
FROM cte
UNION ALL
SELECT item, quantity - picked_quantity, 'Remaining'
FROM cte;

请参见demo

相关问题