我在HackerRank上遇到了一个SQL问题(所以没有秩或窗口函数):
Product_Id Product_Name Category Price Discount Available
1 P-1 C-5 720 10 1
2 P-2 C-1 935 17 1
3 P-3 C-2 588 19 1
4 P-4 C-4 619 5 0
5 P-5 C-1 803 16 1我想知道哪一种产品每种产品的折扣都是最高的。如果一个类别内有相同最大折扣的多个产品,则使用最小product_id打印该产品。
样本输出
C-1 2 17
C-2 3 19
C-4 4 5
C-5 1 10在http://sqlfiddle.com/#!18/1a492d中,我已经把到目前为止尝试过的东西放在这里。我不知道如何获得最大折扣的产品。此外,如果有多个产品具有相同的最大折扣,我如何处理?
发布于 2021-02-03 05:54:34
如果不能使用窗口函数,可以尝试使用子查询。
此示例用于This:
drop table if exists #Product
go
CREATE TABLE #Product
([Product_Id] int, [Product_Name] varchar(50), [Category] varchar(50), [Price] int, [Discount] int, [Available] int)
;
INSERT INTO #Product
([Product_Id], [Product_Name], [Category], [Price], [Discount], [Available])
VALUES
(1, 'P-1', 'C-5',720, 10, 1),
(2, 'P-2', 'C-1',935, 17, 1),
(3, 'P-3', 'C-2',588, 19, 1),
(4, 'P-4', 'C-4',619, 5, 0),
(5, 'P-5', 'C-1',803, 16, 1)
select t2.[Category]
,(select min(t.Product_Id) from #Product t where t.Category=t2.Category and t.Discount=max(t2.Discount))
,max(t2.Discount) from #Product t2
group by [Category]发布于 2021-02-03 06:09:52
此代码返回每组中折扣最多的产品。此代码将产品表链接到返回组和最高折扣价格的动态表。然后,它返回包含该组的产品和折扣以及队列,并在第一行的末尾返回每个组。最后,您可以根据需要对行进行排序。
WITH newTable AS (
SELECT
t.Category,
t.Product_Id,
b.Discount as maxDiscount,
ROW_NUMBER() OVER (
PARTITION BY t.Category
ORDER BY Product_Id DESC
) AS [ROW NUMBER]
FROM Products t
INNER JOIN
(
SELECT MAX(Discount) as maxDiscount, Category
FROM Products
GROUP BY Category
) b ON t.Discount = b.Discount AND t.Category = b.Category)
select Category,Product_Id,maxDiscount from newTable
WHERE newTable.[ROW NUMBER] = 1发布于 2022-05-30 15:57:16
我使用功太郎n根据折扣和product_id在每个类别中获得产品的订单。然后将其放入子查询中,因为我无法在window_function列上运行where子句。
select * from (
select Category,Product_Id,
rank() over (partition by category order by discount desc, product_id asc) as product_rank
from Product) x
where x.product_rank=1
order by category;https://stackoverflow.com/questions/66019044
复制相似问题