如何 select 在大查询中按 ID 分组的前 N 行?
How do I select top N rows grouped by an ID in big query?
我有一个(已更改 items/data)杂货店过道和产品的数据库,我正试图在每个过道中找到有货的前 3 件最昂贵的商品。
我的大查询代码是这样的:
SELECT ROW_NUMBER() OVER (PARTITION BY aisle ORDER BY price DESC) AS high_prices, aisle,
price, product FROM `a_database.shopping.grocery_stores`
WHERE in_stock = TRUE AND high_prices <= 3
GROUP BY aisle
ORDER BY price;
由于 high_prices <= 3
,我收到错误:unrecognized name: high_prices at [2:30]
,但是,我不知道其他方法。
如前所述,我希望输出商店过道上有库存的 4 件最昂贵的商品。但由于上述错误,它不起作用。当我删除 high_prices <= 3
时,我得到的是商店中所有商品的列表以及它们完全乱序的过道。
如何获得使该查询可行的结果?
预期输出类似于此屏幕截图:
我包含了一个示例数据 table:
aisle product in_stock price
1 fresh_chicken TRUE 10
2 frozen_fish TRUE 10
3 truffles TRUE 15
2 cereal TRUE 5
2 cake TRUE 25
3 wine TRUE 30
1 fresh_fish TRUE 15
1 fresh_beef TRUE 10
2 seasonings FALSE 15
3 whiskey TRUE 25
1 whiskey TRUE 40
1 pre_cooked TRUE 30
2 fresh_pie FALSE 10
3 fresh_salad FALSE 5
非常感谢任何帮助或建议。
如果要引用别名,请使用 HAVING
SELECT * FROM
(SELECT ROW_NUMBER() OVER (PARTITION BY aisle ORDER BY price DESC) AS high_prices, aisle,
price, product
FROM `a_database.shopping.grocery_stores`
WHERE in_stock = TRUE
GROUP BY aisle ) t1
WHERE high_prices <= 3
ORDER BY price;
下面使用
select *
from your_table
where in_stock
qualify 3 >= row_number() over(partition by aisle order by price desc)
如果应用于您问题中的示例数据 - 输出为
使用子查询:
select *
from (select row_number() over (partition by aisle order by price desc) row_number,
aisle,
price,
product
from a_database.shopping.grocery_stores
where in_stock is true) a
where row_number <= 3
我有一个(已更改 items/data)杂货店过道和产品的数据库,我正试图在每个过道中找到有货的前 3 件最昂贵的商品。
我的大查询代码是这样的:
SELECT ROW_NUMBER() OVER (PARTITION BY aisle ORDER BY price DESC) AS high_prices, aisle,
price, product FROM `a_database.shopping.grocery_stores`
WHERE in_stock = TRUE AND high_prices <= 3
GROUP BY aisle
ORDER BY price;
由于 high_prices <= 3
,我收到错误:unrecognized name: high_prices at [2:30]
,但是,我不知道其他方法。
如前所述,我希望输出商店过道上有库存的 4 件最昂贵的商品。但由于上述错误,它不起作用。当我删除 high_prices <= 3
时,我得到的是商店中所有商品的列表以及它们完全乱序的过道。
如何获得使该查询可行的结果?
预期输出类似于此屏幕截图:
我包含了一个示例数据 table:
aisle product in_stock price
1 fresh_chicken TRUE 10
2 frozen_fish TRUE 10
3 truffles TRUE 15
2 cereal TRUE 5
2 cake TRUE 25
3 wine TRUE 30
1 fresh_fish TRUE 15
1 fresh_beef TRUE 10
2 seasonings FALSE 15
3 whiskey TRUE 25
1 whiskey TRUE 40
1 pre_cooked TRUE 30
2 fresh_pie FALSE 10
3 fresh_salad FALSE 5
非常感谢任何帮助或建议。
如果要引用别名,请使用 HAVING
SELECT * FROM
(SELECT ROW_NUMBER() OVER (PARTITION BY aisle ORDER BY price DESC) AS high_prices, aisle,
price, product
FROM `a_database.shopping.grocery_stores`
WHERE in_stock = TRUE
GROUP BY aisle ) t1
WHERE high_prices <= 3
ORDER BY price;
下面使用
select *
from your_table
where in_stock
qualify 3 >= row_number() over(partition by aisle order by price desc)
如果应用于您问题中的示例数据 - 输出为
使用子查询:
select *
from (select row_number() over (partition by aisle order by price desc) row_number,
aisle,
price,
product
from a_database.shopping.grocery_stores
where in_stock is true) a
where row_number <= 3