我有一个包含三列的表
Product Version Price
1 1 25
1 2 15
1 3 25
2 1 8
2 2 8
2 3 4
3 1 25
3 2 10
3 3 5
我希望按产品获得最高价格和最高版本。 所以在上面的例子中,结果将有产品1,版本3,price25。产品2,版本2,价格8。
你能让我知道我会怎么做。
我在Teradata
答案 0 :(得分:1)
如果Teradata支持ROW_NUMBER
分析函数:
SELECT
Product,
Version,
Price
FROM (
SELECT
atable.*, /* or specify column names explicitly as necessary */
ROW_NUMBER() OVER (PARTITION BY Product
ORDER BY Price DESC, Version DESC) AS rn
FROM atable
) s
WHERE rn = 1
;
答案 1 :(得分:1)
使用Teradata SQL可以进一步简化:
SELECT * FROM atable
QUALIFY
ROW_NUMBER()
OVER (PARTITION BY Product
ORDER BY Price DESC, Version DESC) = 1;
QUALIFY是标准SQL的Teradata扩展,它类似于GROUP BY的HAVING,它会过滤窗口函数的结果。
答案 2 :(得分:0)
SELECT product
, max(version) as version
, max(price) as price
FROM mytable
GROUP BY product
答案 3 :(得分:0)
以下代码将选择产品,最高版本价格,最高价格价值,并使用GROUP BY
SELECT [product], MAX([version]) as [MaxVersion], MAX([price]) as [MaxPrice]
FROM [NameOfTable]
GROUP BY [product]
有关Max
功能的更多说明:
Max function SQL
答案 4 :(得分:0)
尝试这个
select p.Product, MAX(p.Price), (select MAX(Version) from Products where Product = p.Product and Price = MAX(p.price))
from Products as p
group by p.Product
它返回 (产品,价格,版本) 1 25 3, 2 8 2, 3 25 1