我有一段代码:
SELECT t1.sku_id, t1.putaway_group, t1.shortage, t4.location_id, t4.qty_on_hand
FROM
(WHERE clauses)t1
LEFT JOIN
(
SELECT *
FROM (
SELECT location_id, sku_id, qty_on_hand,
DENSE_RANK() OVER ( PARTITION BY sku_id ORDER BY qty_on_hand DESC ) AS rnk
FROM inventory
WHERE substr(zone_1,1,5) IN ('TOTEB','TOTEC')
)
WHERE rnk = 1
ORDER BY 2 DESC
)t4
ON t3.sku_id = t4.sku_id
其中输出为:
我想要实现的是从location_id返回短缺所需的行数。例如,如果短缺为-84,则将THEN作为SKU的输出:02295441我想返回6行,因为(6*16 = 96)这将弥补我的不足。不太确定是否可能,或者如果是,那么如何写一个where/having子句来限制输出行。目前我只是通过excel中的power query来做,但只是想知道是否可能直接从sql中。提前感谢。
2条答案
按热度按时间ego6inou1#
You can use the
SUM
analytic function:Which, for the sample data:
Outputs:
| SKU_ID | PUTAWAY_GROUP | SHORTAGE | LOCATION_ID | QTY_ON_HAND |
| ------------ | ------------ | ------------ | ------------ | ------------ |
| SKU1 | TEXTILES | -84 | 4 | 16 |
| SKU1 | TEXTILES | -84 | 5 | 16 |
| SKU1 | TEXTILES | -84 | 6 | 16 |
| SKU1 | TEXTILES | -84 | 7 | 16 |
| SKU1 | TEXTILES | -84 | 8 | 16 |
| SKU1 | TEXTILES | -84 | 9 | 16 |
| SKU2 | PLASTICS | -13 | 6 | 6 |
| SKU2 | PLASTICS | -13 | 5 | 5 |
| SKU2 | PLASTICS | -13 | 4 | 4 |
fiddle
l7wslrjt2#
由于缺乏样本数据,我的CTE代表(简化)结果,你目前有;如果对它应用
row_number
函数,然后返回满足所述条件的行(参见第22行),则可能得到所需结果: