繁体   English   中英

Postgres,根据条件将一行拆分为多行

[英]Postgres, split one row into multiple rows with conditions

我有一个表order_item像这样:

  | sku | quantity | subtotal |
  |-----|----------|----------|
  |  A  |        1 |   25.00  |
  |  B  |        2 |   40.00  |
  |  C  |        3 |   45.00  |

有什么方法可以从order_item中选择“ unit order_item”行,结果如下:

  | sku | unit_price |
  |-----|------------|
  |  A  |   25.00    |
  |  B  |   20.00    |
  |  B  |   20.00    |
  |  C  |   15.00    |
  |  C  |   15.00    |
  |  C  |   15.00    |

其中结果行计数的sku是order_item中的数量,而unit_price是(小计/数量)?

您可以为此使用generate_series()

select oi.sku, oi.subtotal / oi.quantity as unit_price
from order_item oi
  cross join lateral generate_series(1,oi.quantity)
order by oi.sku;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM