我在 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
在 this SQL Fiddle ,我已将迄今为止尝试过的内容放在这里。我不知道如何获得最大折扣的产品。另外,如果有多个产品具有相同的最高折扣,我该如何处理?
最佳答案
如果无法使用窗口函数,可以尝试使用子查询。
此示例适用于 T-SQL:
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]
关于sql - 如何在 HackerRank 上使用 SQL 查找具有最大折扣的产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66019044/