选择如何在sql中查询行
我有一个用例,比如选择如何在sql中查询行,sql,postgresql,greatest-n-per-group,Sql,Postgresql,Greatest N Per Group,我有一个用例,比如 a 3 a 4 a 5 a 6 a 5 b 3 b 5 b 3 如何获得这样的输出 a 4 a 5 b 5 b 3 选择a和b的高位数字,但仅选择2行 这就是我现在写的查询,似乎不起作用 SELECT id, barcode, actualsku, inventorycount FROM ( SELECT pallet.id AS id, pallet.barcode
a 3
a 4
a 5
a 6
a 5
b 3
b 5
b 3
如何获得这样的输出
a 4
a 5
b 5
b 3
选择a和b的高位数字,但仅选择2行
这就是我现在写的查询,似乎不起作用
SELECT id, barcode, actualsku, inventorycount
FROM ( SELECT pallet.id AS id,
pallet.barcode AS barcode,
inventoryunit.sku AS actualsku,
Count(inventoryunit.id) AS inventorycount
FROM (SELECT *
FROM mft.asset
WHERE container_type = 'PALLET'
AND location_type = 'PRIME' :: mft.location_type
AND is_deleted = FALSE
AND ( attributes ->> 'sku' :: text ) IS NOT NULL) pallet
LEFT OUTER JOIN (SELECT *
FROM mft.asset
WHERE asset_type = 'INVENTORYUNIT' :: mft.asset_type
AND is_deleted = FALSE) inventoryunit
ON pallet.id = inventoryunit.parent_id
GROUP BY inventoryunit.sku,
pallet.id,
pallet.barcode,
pallet.attributes ) test
WHERE (SELECT COUNT(*) FROM test as t
WHERE t.actualsku = test.actualsku
AND t.inventorycount <= test.inventorycount
) <= 2
这通常使用窗口函数完成:
select col1, col2
from (
select col1, col2,
row_number() over (partition by col1 order by col2 desc) as rnk
from the_table
) t
where rnk <= 2
order by col1, col2;
在线示例:如何选择这两行?结果背后的逻辑是什么?这是可能的重复项的重复项。您是否尝试过任何查询?